-- ============================================================
-- Phase 3 数据库迁移脚本
-- 执行方式: psql -U postgres -d crm_erp -f migration_phase3.sql
-- ============================================================

-- ────── 1. AI 对话持久化 ──────
CREATE TABLE IF NOT EXISTS ai_chat_sessions (
    id          UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    user_id     UUID NOT NULL REFERENCES sys_users(id),
    role        VARCHAR(10) NOT NULL CHECK (role IN ('user', 'assistant')),
    content     TEXT NOT NULL,
    msg_type    VARCHAR(20) DEFAULT 'text',
    metadata    JSONB DEFAULT '{}',
    created_at  TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

COMMENT ON TABLE  ai_chat_sessions IS 'AI 悬浮球对话历史（按用户分区）';
CREATE INDEX IF NOT EXISTS idx_chat_user_time ON ai_chat_sessions(user_id, created_at DESC);

-- ────── 2. 客户 AI 画像字段 ──────
DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM information_schema.columns
        WHERE table_name = 'crm_customers' AND column_name = 'ai_persona'
    ) THEN
        ALTER TABLE crm_customers ADD COLUMN ai_persona JSONB DEFAULT '{}';
        COMMENT ON COLUMN crm_customers.ai_persona IS 'AI 提炼的客户画像（痛点/偏好/购买习惯等）';
    END IF;
END $$;

-- ────── 3. 销售日志表 ──────
CREATE TABLE IF NOT EXISTS sales_logs (
    id              UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    salesperson_id  UUID NOT NULL REFERENCES sys_users(id),
    customer_id     UUID REFERENCES crm_customers(id),
    content         TEXT NOT NULL,
    log_date        DATE DEFAULT CURRENT_DATE,
    ai_processed    BOOLEAN DEFAULT FALSE,
    created_at      TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at      TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    is_deleted      BOOLEAN DEFAULT FALSE
);

COMMENT ON TABLE  sales_logs IS '销售日志表（一源多用数据源）';
CREATE INDEX IF NOT EXISTS idx_slog_sales ON sales_logs(salesperson_id) WHERE is_deleted = FALSE;
CREATE INDEX IF NOT EXISTS idx_slog_cust  ON sales_logs(customer_id)    WHERE is_deleted = FALSE;
CREATE INDEX IF NOT EXISTS idx_slog_date  ON sales_logs(log_date)       WHERE is_deleted = FALSE;

CREATE TRIGGER trg_slog_updated
    BEFORE UPDATE ON sales_logs
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();

-- ────── 4. AI 报告草稿表 ──────
CREATE TABLE IF NOT EXISTS ai_report_drafts (
    id              UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
    author_id       UUID NOT NULL REFERENCES sys_users(id),
    report_type     VARCHAR(20) NOT NULL CHECK (report_type IN ('weekly', 'monthly')),
    period_start    DATE NOT NULL,
    period_end      DATE NOT NULL,
    content_md      TEXT NOT NULL,
    status          VARCHAR(20) DEFAULT 'draft' CHECK (status IN ('draft', 'confirmed', 'archived')),
    created_at      TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at      TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    is_deleted      BOOLEAN DEFAULT FALSE
);

COMMENT ON TABLE  ai_report_drafts IS 'AI 生成的报告草稿（周报/月报）';
CREATE INDEX IF NOT EXISTS idx_report_author ON ai_report_drafts(author_id) WHERE is_deleted = FALSE;
CREATE INDEX IF NOT EXISTS idx_report_period ON ai_report_drafts(period_start, period_end);

CREATE TRIGGER trg_report_updated
    BEFORE UPDATE ON ai_report_drafts
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();

-- ────── 完成 ──────
-- 新增: ai_chat_sessions, sales_logs, ai_report_drafts (3 张表)
-- 修改: crm_customers 增加 ai_persona JSONB 字段
