-- 智能客服系统数据库初始化脚本
-- 创建时间: 2026-02-27
-- 作者: 小弟 (大哥的AI助手)

-- 启用UUID扩展
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

-- 1. 租户表
CREATE TABLE tenants (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100) NOT NULL UNIQUE,
    display_name VARCHAR(200),
    description TEXT,
    domain VARCHAR(100) UNIQUE,
    email VARCHAR(100) NOT NULL,
    phone VARCHAR(20),
    
    -- 订阅信息
    plan VARCHAR(50) DEFAULT 'free',
    status VARCHAR(20) DEFAULT 'active',
    expires_at TIMESTAMP WITH TIME ZONE,
    
    -- 资源配置
    max_users INT DEFAULT 10,
    max_agents INT DEFAULT 5,
    max_storage BIGINT DEFAULT 1073741824, -- 1GB
    max_api_calls INT DEFAULT 1000,
    
    -- 使用统计
    user_count INT DEFAULT 0,
    agent_count INT DEFAULT 0,
    storage_used BIGINT DEFAULT 0,
    api_calls_used INT DEFAULT 0,
    
    -- 配置
    config JSONB DEFAULT '{}',
    
    -- 时间戳
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    deleted_at TIMESTAMP WITH TIME ZONE
);

-- 创建索引
CREATE INDEX idx_tenants_status ON tenants(status);
CREATE INDEX idx_tenants_domain ON tenants(domain);
CREATE INDEX idx_tenants_deleted_at ON tenants(deleted_at);

-- 2. 用户表（多租户共享）
CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    tenant_id INT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
    username VARCHAR(50) NOT NULL,
    email VARCHAR(100) NOT NULL,
    password VARCHAR(255) NOT NULL,
    phone VARCHAR(20),
    
    -- 个人信息
    full_name VARCHAR(100),
    avatar VARCHAR(255),
    bio TEXT,
    
    -- 角色和权限
    role VARCHAR(20) DEFAULT 'user',
    status VARCHAR(20) DEFAULT 'active',
    is_verified BOOLEAN DEFAULT FALSE,
    
    -- 最后活动
    last_login_at TIMESTAMP WITH TIME ZONE,
    last_ip VARCHAR(45),
    
    -- 配置
    preferences JSONB DEFAULT '{}',
    
    -- 时间戳
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    deleted_at TIMESTAMP WITH TIME ZONE
);

-- 创建复合索引和唯一约束
CREATE UNIQUE INDEX idx_users_email_tenant ON users(email, tenant_id);
CREATE INDEX idx_users_tenant_id ON users(tenant_id);
CREATE INDEX idx_users_username ON users(username);
CREATE INDEX idx_users_role ON users(role);
CREATE INDEX idx_users_status ON users(status);
CREATE INDEX idx_users_deleted_at ON users(deleted_at);

-- 3. 客服坐席表
CREATE TABLE agents (
    id SERIAL PRIMARY KEY,
    tenant_id INT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
    user_id INT NOT NULL UNIQUE REFERENCES users(id) ON DELETE CASCADE,
    
    -- 坐席信息
    agent_id VARCHAR(50) NOT NULL UNIQUE,
    department VARCHAR(100),
    title VARCHAR(100),
    skills JSONB DEFAULT '[]',
    
    -- 工作状态
    status VARCHAR(20) DEFAULT 'offline',
    max_chats INT DEFAULT 5,
    current_chats INT DEFAULT 0,
    
    -- 绩效统计
    total_chats INT DEFAULT 0,
    avg_rating DECIMAL(3,2) DEFAULT 0,
    response_time_avg INT DEFAULT 0,
    
    -- 工作时间
    work_schedule JSONB DEFAULT '{}',
    
    -- 时间戳
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

-- 创建索引
CREATE INDEX idx_agents_tenant_id ON agents(tenant_id);
CREATE INDEX idx_agents_user_id ON agents(user_id);
CREATE INDEX idx_agents_status ON agents(status);
CREATE INDEX idx_agents_agent_id ON agents(agent_id);

-- 4. 会话表
CREATE TABLE conversations (
    id SERIAL PRIMARY KEY,
    tenant_id INT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
    channel VARCHAR(50) NOT NULL,
    type VARCHAR(20) NOT NULL,
    
    -- 参与者
    customer_id INT REFERENCES users(id) ON DELETE SET NULL,
    customer_name VARCHAR(100),
    customer_email VARCHAR(100),
    customer_phone VARCHAR(20),
    
    agent_id INT REFERENCES agents(id) ON DELETE SET NULL,
    department VARCHAR(100),
    
    -- 会话信息
    title VARCHAR(200),
    description TEXT,
    tags JSONB DEFAULT '[]',
    priority VARCHAR(20) DEFAULT 'normal',
    
    -- 状态
    status VARCHAR(20) DEFAULT 'open',
    source VARCHAR(100),
    referrer VARCHAR(500),
    
    -- 统计
    message_count INT DEFAULT 0,
    first_response_at TIMESTAMP WITH TIME ZONE,
    first_response_duration INT DEFAULT 0,
    resolution_at TIMESTAMP WITH TIME ZONE,
    resolution_duration INT DEFAULT 0,
    
    -- 满意度
    rating INT CHECK (rating >= 1 AND rating <= 5),
    rating_comment TEXT,
    
    -- 元数据
    metadata JSONB DEFAULT '{}',
    
    -- 时间戳
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    closed_at TIMESTAMP WITH TIME ZONE
);

-- 创建索引
CREATE INDEX idx_conversations_tenant_id ON conversations(tenant_id);
CREATE INDEX idx_conversations_customer_id ON conversations(customer_id);
CREATE INDEX idx_conversations_agent_id ON conversations(agent_id);
CREATE INDEX idx_conversations_status ON conversations(status);
CREATE INDEX idx_conversations_priority ON conversations(priority);
CREATE INDEX idx_conversations_created_at ON conversations(created_at);

-- 5. 消息表
CREATE TABLE messages (
    id SERIAL PRIMARY KEY,
    tenant_id INT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
    conversation_id INT NOT NULL REFERENCES conversations(id) ON DELETE CASCADE,
    
    -- 发送者信息
    sender_type VARCHAR(20) NOT NULL,
    sender_id INT REFERENCES users(id) ON DELETE SET NULL,
    sender_name VARCHAR(100),
    sender_avatar VARCHAR(255),
    
    -- 消息内容
    content_type VARCHAR(50) DEFAULT 'text',
    content TEXT NOT NULL,
    rich_content JSONB DEFAULT '{}',
    
    -- AI相关
    is_ai_response BOOLEAN DEFAULT FALSE,
    ai_model VARCHAR(100),
    ai_prompt_tokens INT DEFAULT 0,
    ai_completion_tokens INT DEFAULT 0,
    ai_total_tokens INT DEFAULT 0,
    
    -- 状态
    status VARCHAR(20) DEFAULT 'sent',
    read_by JSONB DEFAULT '[]',
    read_at TIMESTAMP WITH TIME ZONE,
    
    -- 回复引用
    reply_to_id INT REFERENCES messages(id) ON DELETE SET NULL,
    
    -- 时间戳
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

-- 创建索引
CREATE INDEX idx_messages_tenant_id ON messages(tenant_id);
CREATE INDEX idx_messages_conversation_id ON messages(conversation_id);
CREATE INDEX idx_messages_sender_id ON messages(sender_id);
CREATE INDEX idx_messages_sender_type ON messages(sender_type);
CREATE INDEX idx_messages_created_at ON messages(created_at);
CREATE INDEX idx_messages_reply_to_id ON messages(reply_to_id);

-- 6. 附件表
CREATE TABLE attachments (
    id SERIAL PRIMARY KEY,
    tenant_id INT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
    message_id INT NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
    
    -- 文件信息
    name VARCHAR(255) NOT NULL,
    type VARCHAR(100) NOT NULL,
    size BIGINT NOT NULL,
    url VARCHAR(500) NOT NULL,
    thumbnail_url VARCHAR(500),
    
    -- 元数据
    width INT,
    height INT,
    duration INT,
    
    -- 时间戳
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

-- 创建索引
CREATE INDEX idx_attachments_tenant_id ON attachments(tenant_id);
CREATE INDEX idx_attachments_message_id ON attachments(message_id);

-- 7. 工单表
CREATE TABLE tickets (
    id SERIAL PRIMARY KEY,
    tenant_id INT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
    conversation_id INT REFERENCES conversations(id) ON DELETE SET NULL,
    
    -- 工单信息
    ticket_number VARCHAR(50) NOT NULL UNIQUE,
    title VARCHAR(200) NOT NULL,
    description TEXT NOT NULL,
    category VARCHAR(100),
    subcategory VARCHAR(100),
    tags JSONB DEFAULT '[]',
    priority VARCHAR(20) DEFAULT 'normal',
    
    -- 参与者
    customer_id INT REFERENCES users(id) ON DELETE SET NULL,
    customer_name VARCHAR(100),
    customer_email VARCHAR(100),
    
    assigned_agent_id INT REFERENCES agents(id) ON DELETE SET NULL,
    assigned_department VARCHAR(100),
    
    -- 状态
    status VARCHAR(20) DEFAULT 'open',
    source VARCHAR(100),
    
    -- SLA管理
    sla_level VARCHAR(50),
    due_at TIMESTAMP WITH TIME ZONE,
    first_response_due_at TIMESTAMP WITH TIME ZONE,
    resolution_due_at TIMESTAMP WITH TIME ZONE,
    
    -- 统计
    first_response_at TIMESTAMP WITH TIME ZONE,
    first_response_duration INT DEFAULT 0,
    resolution_at TIMESTAMP WITH TIME ZONE,
    resolution_duration INT DEFAULT 0,
    
    -- 满意度
    rating INT CHECK (rating >= 1 AND rating <= 5),
    rating_comment TEXT,
    
    -- 元数据
    metadata JSONB DEFAULT '{}',
    
    -- 时间戳
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    closed_at TIMESTAMP WITH TIME ZONE
);

-- 创建索引
CREATE INDEX idx_tickets_tenant_id ON tickets(tenant_id);
CREATE INDEX idx_tickets_ticket_number ON tickets(ticket_number);
CREATE INDEX idx_tickets_customer_id ON tickets(customer_id);
CREATE INDEX idx_tickets_assigned_agent_id ON tickets(assigned_agent_id);
CREATE INDEX idx_tickets_status ON tickets(status);
CREATE INDEX idx_tickets_priority ON tickets(priority);
CREATE INDEX idx_tickets_due_at ON tickets(due_at);
CREATE INDEX idx_tickets_created_at ON tickets(created_at);

-- 8. 知识库表
CREATE TABLE knowledge_base (
    id SERIAL PRIMARY KEY,
    tenant_id INT NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
    
    -- 知识条目
    title VARCHAR(200) NOT NULL,
    content TEXT NOT NULL,
    summary TEXT,
    category VARCHAR(100),
    tags JSONB DEFAULT '[]',
    
    -- 状态
    status VARCHAR(20) DEFAULT 'draft',
    visibility VARCHAR(20) DEFAULT 'private',
    
    -- 统计
    view_count INT DEFAULT 0,
    helpful_count INT DEFAULT 0,
    not_helpful_count INT DEFAULT 0,
    
    -- AI训练
    is_trained BOOLEAN DEFAULT FALSE,
    training_status VARCHAR(50),
    last_trained_at TIMESTAMP WITH TIME ZONE,
    
    -- 元数据
    metadata JSONB DEFAULT '{}',
    
    -- 作者信息
    author_id INT REFERENCES users(id) ON DELETE SET NULL,
    author_name VARCHAR(100),
    
    -- 时间戳
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    published_at TIMESTAMP WITH TIME ZONE
);

-- 创建索引
CREATE INDEX idx_knowledge_base_tenant_id ON knowledge_base(tenant_id);
CREATE INDEX idx_knowledge_base_category ON knowledge_base(category);
CREATE INDEX idx_knowledge_base_status ON knowledge_base(status);
CREATE INDEX idx_knowledge_base_visibility ON knowledge_base(visibility);
CREATE INDEX idx_knowledge_base_tags ON knowledge_base USING GIN(tags);

-- 9. 系统配置表
CREATE TABLE system_configs (
    id SERIAL PRIMARY KEY,
    tenant_id INT REFERENCES tenants(id) ON DELETE CASCADE,
    config_key VARCHAR(100) NOT NULL,
    config_value JSONB NOT NULL,
    config_type VARCHAR(50) DEFAULT 'string',
    description TEXT,
    
    -- 作用域
    scope VARCHAR(50) DEFAULT 'tenant', -- system, tenant, user
    is_public BOOLEAN DEFAULT FALSE,
    
    -- 时间戳
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

-- 创建唯一约束和索引
CREATE UNIQUE INDEX idx_system_configs_key_tenant ON system_configs(config_key, tenant_id);
CREATE INDEX idx_system_configs_scope ON system_configs(scope);

-- 10. 审计日志表
CREATE TABLE audit_logs (
    id SERIAL PRIMARY KEY,
    tenant_id INT REFERENCES tenants(id) ON DELETE CASCADE,
    
    -- 操作信息
    action VARCHAR(100) NOT NULL,
    resource_type VARCHAR(50) NOT NULL,
    resource_id VARCHAR(100),
    resource_name VARCHAR(200),
    
    -- 用户信息
    user_id INT REFERENCES users(id) ON DELETE SET NULL,
    user_name VARCHAR(100),
    user_ip VARCHAR(45),
    user_agent TEXT,
    
    -- 变更详情
    old_values JSONB,
    new_values JSONB,
    changes JSONB,
    
    -- 结果
    status VARCHAR(20) DEFAULT 'success',
    error_message TEXT,
    
    -- 时间戳
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

-- 创建索引
CREATE INDEX idx_audit_logs_tenant_id ON audit_logs(tenant_id);
CREATE INDEX idx_audit_logs_user_id ON audit_logs(user_id);
CREATE INDEX idx_audit_logs_action ON audit_logs(action);
CREATE INDEX idx_audit_logs_resource_type ON audit_logs(resource_type);
CREATE INDEX idx_audit_logs_created_at ON audit_logs(created_at);

-- 插入默认系统配置
INSERT INTO system_configs (config_key, config_value, config_type, description, scope, is_public)
VALUES 
    ('system.name', '"智能客服系统"', 'string', '系统名称', 'system', TRUE),
    ('system.version', '"1.0.0"', 'string', '系统版本', 'system', TRUE),
    ('system.maintenance', 'false', 'boolean', '系统维护状态', 'system', TRUE),
    ('ai.default_model', '"gpt-3.5-turbo"', 'string', '默认AI模型', 'system', FALSE),
    ('ai.max_tokens', '1000', 'number', 'AI最大token数', 'system', FALSE),
    ('ai.temperature', '0.7', 'number', 'AI温度参数', 'system', FALSE),
    ('sla.first_response', '3600', 'number', '首次响应SLA（秒）', 'system', FALSE),
    ('sla.resolution', '86400', 'number', '解决SLA（秒）', 'system', FALSE);

-- 创建默认管理员租户
INSERT INTO tenants (name, display_name, description, domain, email, phone, plan, max_users, max_agents)
VALUES 
    ('admin', '系统管理租户', '系统默认管理租户', 'admin.local', 'admin@example.com', '13800138000', 'enterprise', 100, 50);

-- 创建默认管理员用户
INSERT INTO users (tenant_id, username, email, password, full_name, role, is_verified)
SELECT 
    id, 
    'admin', 
    'admin@example.com', 
    -- 密码: admin123 (bcrypt hash)
    '$2a$10$N9qo8uLOickgx2ZMRZoMye3Z7c7K8pB7J7B7J7B7J7B7J7B7J7B7J', 
    '系统管理员', 
    'super_admin', 
    TRUE
FROM tenants WHERE name = 'admin';

-- 输出完成信息
SELECT '数据库初始化完成！' AS message;
