-- 合同起草功能数据库迁移脚本
-- 创建时间: 2025-01-04

-- 1. 创建起草合同表
CREATE TABLE IF NOT EXISTS drafted_contracts (
  id SERIAL PRIMARY KEY,
  template_id INTEGER NOT NULL,
  file_path TEXT NOT NULL,
  title TEXT NOT NULL,
  placeholder_values JSONB DEFAULT '{}'::jsonb,
  status TEXT DEFAULT 'draft' CHECK (status IN ('draft', 'completed', 'archived')),
  created_by INTEGER,
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW(),

  CONSTRAINT fk_template
    FOREIGN KEY (template_id)
    REFERENCES contract_templates(id)
    ON DELETE CASCADE,

  CONSTRAINT fk_created_by
    FOREIGN KEY (created_by)
    REFERENCES auth.users(id)
    ON DELETE SET NULL
);

-- 2. 创建索引优化查询性能
CREATE INDEX idx_drafted_contracts_template_id ON drafted_contracts(template_id);
CREATE INDEX idx_drafted_contracts_created_by ON drafted_contracts(created_by);
CREATE INDEX idx_drafted_contracts_status ON drafted_contracts(status);
CREATE INDEX idx_drafted_contracts_created_at ON drafted_contracts(created_at DESC);

-- 3. 创建更新时间触发器
CREATE OR REPLACE FUNCTION update_drafted_contracts_updated_at()
RETURNS TRIGGER AS $$
BEGIN
  NEW.updated_at = NOW();
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER trigger_update_drafted_contracts_updated_at
  BEFORE UPDATE ON drafted_contracts
  FOR EACH ROW
  EXECUTE FUNCTION update_drafted_contracts_updated_at();

-- 4. 添加注释
COMMENT ON TABLE drafted_contracts IS '起草的合同记录';
COMMENT ON COLUMN drafted_contracts.id IS '主键ID';
COMMENT ON COLUMN drafted_contracts.template_id IS '关联的合同模板ID';
COMMENT ON COLUMN drafted_contracts.file_path IS '起草后的文件路径（MinIO）';
COMMENT ON COLUMN drafted_contracts.title IS '合同标题';
COMMENT ON COLUMN drafted_contracts.placeholder_values IS '占位符填充值（JSON格式）';
COMMENT ON COLUMN drafted_contracts.status IS '状态：draft-草稿，completed-已完成，archived-已归档';
COMMENT ON COLUMN drafted_contracts.created_by IS '创建人用户ID';
COMMENT ON COLUMN drafted_contracts.created_at IS '创建时间';
COMMENT ON COLUMN drafted_contracts.updated_at IS '更新时间';

-- 5. 为 contract_templates 表添加占位符配置字段
ALTER TABLE contract_templates
ADD COLUMN IF NOT EXISTS placeholder_schema JSONB DEFAULT NULL;

COMMENT ON COLUMN contract_templates.placeholder_schema IS '占位符配置Schema（JSON格式）';

-- 6. 示例：为测试模板添加占位符配置（可选，根据实际情况调整）
-- UPDATE contract_templates
-- SET placeholder_schema = '{
--   "fields": [
--     {"key": "甲方名称", "label": "甲方名称", "type": "text", "required": true, "group": "甲方信息"},
--     {"key": "甲方地址", "label": "甲方地址", "type": "text", "required": true, "group": "甲方信息"},
--     {"key": "甲方法定代表人", "label": "法定代表人", "type": "text", "required": true, "group": "甲方信息"},
--     {"key": "甲方联系电话", "label": "联系电话", "type": "tel", "required": true, "group": "甲方信息"},
--     {"key": "乙方名称", "label": "乙方名称", "type": "text", "required": true, "group": "乙方信息"},
--     {"key": "乙方地址", "label": "乙方地址", "type": "text", "required": true, "group": "乙方信息"},
--     {"key": "乙方法定代表人", "label": "法定代表人", "type": "text", "required": true, "group": "乙方信息"},
--     {"key": "乙方联系电话", "label": "联系电话", "type": "tel", "required": true, "group": "乙方信息"},
--     {"key": "合同金额", "label": "合同金额（元）", "type": "number", "required": true, "group": "合同条款"},
--     {"key": "签订日期", "label": "签订日期", "type": "date", "required": true, "group": "合同条款"},
--     {"key": "合同编号", "label": "合同编号", "type": "text", "required": false, "group": "基本信息"}
--   ]
-- }'::jsonb
-- WHERE id = 1;
