-- 宇之然内容创作平台 - 数据库初始化脚本

-- 创建扩展（如果需要）
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
CREATE EXTENSION IF NOT EXISTS "pgcrypto";

-- 创建管理员用户（如果不存在）
INSERT INTO users (username, password_hash, role, created_at)
VALUES ('admin', '$2b$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/LewdBPj9X7F5Z4nO', 'admin', NOW())
ON CONFLICT DO NOTHING;

-- 创建示例选题数据
INSERT INTO topics (title, field, priority_score, status, compliance_score, created_at)
VALUES 
('人工智能发展趋势分析', '科技', 15, '待处理', 85, NOW()),
('数字化转型对企业的影响', '商业', 12, '待审查', 92, NOW()),
('区块链技术在金融领域的应用', '金融科技', 18, '待发布', 78, NOW()),
('绿色能源与可持续发展', '环保', 10, '已发布', 95, NOW())
ON CONFLICT DO NOTHING;

-- 创建审计日志表（如果不存在）
CREATE TABLE IF NOT EXISTS audit_logs (
    id SERIAL PRIMARY KEY,
    user_id INTEGER REFERENCES users(id),
    action VARCHAR(50) NOT NULL,
    resource_type VARCHAR(50),
    resource_id INTEGER,
    details TEXT,
    ip_address INET,
    user_agent TEXT,
    timestamp TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- 创建生成任务表（如果不存在）
CREATE TABLE IF NOT EXISTS generate_tasks (
    id SERIAL PRIMARY KEY,
    topic_id INTEGER REFERENCES topics(id),
    status VARCHAR(20) DEFAULT 'pending',
    result JSONB,
    created_by INTEGER REFERENCES users(id),
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- 创建发布记录表（如果不存在）
CREATE TABLE IF NOT EXISTS publish_records (
    id SERIAL PRIMARY KEY,
    topic_id INTEGER REFERENCES topics(id),
    platform VARCHAR(50),
    url TEXT,
    status VARCHAR(20) DEFAULT 'success',
    error_message TEXT,
    created_by INTEGER REFERENCES users(id),
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- 创建索引优化查询性能
CREATE INDEX IF NOT EXISTS idx_topics_status ON topics(status);
CREATE INDEX IF NOT EXISTS idx_topics_created_at ON topics(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_audit_logs_timestamp ON audit_logs(timestamp DESC);
CREATE INDEX IF NOT EXISTS idx_generate_tasks_topic_id ON generate_tasks(topic_id);
CREATE INDEX IF NOT EXISTS idx_publish_records_topic_id ON publish_records(topic_id);

-- 更新触发器函数（如果不存在）
CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = NOW();
    RETURN NEW;
END;
$$ language 'plpgsql';

-- 为topics表添加触发器
DROP TRIGGER IF EXISTS update_topics_updated_at ON topics;
CREATE TRIGGER update_topics_updated_at BEFORE UPDATE ON topics
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();

-- 插入初始审计日志
INSERT INTO audit_logs (user_id, action, resource_type, resource_id, details, timestamp)
SELECT 
    u.id,
    'system_init',
    'database',
    NULL,
    '数据库初始化完成',
    NOW()
FROM users u 
WHERE u.username = 'admin'
ON CONFLICT DO NOTHING;

-- 验证数据
DO $$
BEGIN
    RAISE NOTICE '数据库初始化完成';
    RAISE NOTICE '管理员账号: admin';
    RAISE NOTICE '密码: Admin@2026!';
    RAISE NOTICE 'API地址: http://localhost:8001';
    RAISE NOTICE '前端地址: http://localhost:8000';
END $$;