-- ============================================
-- LinkShare Blog - 数据库初始化脚本
-- ============================================
-- 用途: 在 PostgreSQL 首次启动时创建必要扩展和配置
-- 自动由 docker-compose 执行

-- 创建 pgcrypto 扩展 (用于密码哈希等)
CREATE EXTENSION IF NOT EXISTS pgcrypto;

-- 设置时区
SET timezone = 'UTC';

-- 授予 blog 用户对 public 模式的所有权限
-- 这是必要的，因为 Prisma 需要创建表、索引等
GRANT ALL PRIVILEGES ON SCHEMA public TO blog;
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO blog;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO blog;
GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public TO blog;

-- 确保未来的表也继承权限
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL PRIVILEGES ON TABLES TO blog;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL PRIVILEGES ON SEQUENCES TO blog;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL PRIVILEGES ON FUNCTIONS TO blog;

-- 输出完成信息
DO $$
BEGIN
    RAISE NOTICE 'Database initialization completed successfully!';
    RAISE NOTICE 'Extensions: pgcrypto';
    RAISE NOTICE 'Permissions granted to user: blog';
END $$;
