-- ═══════════════════════════════════════════════════════════════
-- V5.0 ERP 智能化升级 — 底层数据物理基座重构
-- ═══════════════════════════════════════════════════════════════

-- 1. 创建 crm_contacts 子表 (联系人维度，1:N 映射到 crm_customers)
CREATE TABLE IF NOT EXISTS crm_contacts (
    id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    customer_id     UUID NOT NULL REFERENCES crm_customers(id) ON DELETE CASCADE,
    name            VARCHAR(100) NOT NULL,
    phone           VARCHAR(30),
    title           VARCHAR(100),                           -- 职位/头衔
    ai_buyer_persona JSONB DEFAULT '{}'::jsonb,             -- 联系人级 AI 画像
    is_deleted      BOOLEAN DEFAULT FALSE,
    created_at      TIMESTAMPTZ DEFAULT NOW(),
    updated_at      TIMESTAMPTZ DEFAULT NOW()
);

COMMENT ON TABLE  crm_contacts IS '客户联系人子表 (V5.0)';
COMMENT ON COLUMN crm_contacts.customer_id      IS '关联的客户 UUID';
COMMENT ON COLUMN crm_contacts.name             IS '联系人姓名';
COMMENT ON COLUMN crm_contacts.phone            IS '联系人电话';
COMMENT ON COLUMN crm_contacts.title            IS '职位/头衔';
COMMENT ON COLUMN crm_contacts.ai_buyer_persona IS '联系人个体画像 JSONB：role / kpi / preference';

-- 索引
CREATE INDEX IF NOT EXISTS idx_contacts_customer   ON crm_contacts(customer_id);
CREATE INDEX IF NOT EXISTS idx_contacts_not_deleted ON crm_contacts(customer_id) WHERE is_deleted = FALSE;

-- updated_at 自动更新触发器
CREATE OR REPLACE FUNCTION trg_contacts_updated() RETURNS TRIGGER AS $$
BEGIN NEW.updated_at = NOW(); RETURN NEW; END;
$$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS trg_crm_contacts_updated ON crm_contacts;
CREATE TRIGGER trg_crm_contacts_updated
    BEFORE UPDATE ON crm_contacts
    FOR EACH ROW EXECUTE FUNCTION trg_contacts_updated();


-- 2. sales_logs 新增 contact_ids 字段 (JSONB Array，允许一次沟通涉及多个联系人)
ALTER TABLE sales_logs ADD COLUMN IF NOT EXISTS contact_ids JSONB DEFAULT '[]'::jsonb;
COMMENT ON COLUMN sales_logs.contact_ids IS '本次沟通涉及的联系人 UUID 列表 (JSONB Array)';
