BEGIN;

-- ============================================================================
-- LeAudit Platform Contract Template Schema
-- 目标：
--   1. 在主库 leaudit_platform 创建合同模板分类表
--   2. 在主库 leaudit_platform 创建合同模板表
--   3. 补齐索引与基础约束
-- 说明：
--   - 本脚本不依赖旧库 docauditai
--   - 幂等脚本，可重复执行
-- ============================================================================

CREATE TABLE IF NOT EXISTS public.contract_categories (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    icon VARCHAR(100) NULL,
    description TEXT NULL,
    sort_order INTEGER NOT NULL DEFAULT 0,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE UNIQUE INDEX IF NOT EXISTS idx_contract_categories_name
    ON public.contract_categories(name);

CREATE TABLE IF NOT EXISTS public.contract_templates (
    id BIGSERIAL PRIMARY KEY,
    template_code VARCHAR(50) NOT NULL,
    title VARCHAR(200) NOT NULL,
    category_id INTEGER NOT NULL REFERENCES public.contract_categories(id) ON DELETE RESTRICT,
    description TEXT NULL,
    file_path VARCHAR(500) NULL,
    file_format VARCHAR(10) NOT NULL,
    is_featured BOOLEAN NOT NULL DEFAULT FALSE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    pdf_file_path VARCHAR(500) NULL
);

CREATE UNIQUE INDEX IF NOT EXISTS idx_contract_templates_code
    ON public.contract_templates(template_code);

CREATE INDEX IF NOT EXISTS idx_contract_templates_category_id
    ON public.contract_templates(category_id);

CREATE INDEX IF NOT EXISTS idx_contract_templates_updated_at
    ON public.contract_templates(updated_at DESC);

COMMENT ON TABLE public.contract_categories IS '合同模板分类表';
COMMENT ON COLUMN public.contract_categories.name IS '分类名称';
COMMENT ON COLUMN public.contract_categories.icon IS '分类图标';
COMMENT ON COLUMN public.contract_categories.description IS '分类描述';
COMMENT ON COLUMN public.contract_categories.sort_order IS '排序值';

COMMENT ON TABLE public.contract_templates IS '合同模板主表';
COMMENT ON COLUMN public.contract_templates.template_code IS '模板编码';
COMMENT ON COLUMN public.contract_templates.title IS '模板标题';
COMMENT ON COLUMN public.contract_templates.category_id IS '所属分类ID';
COMMENT ON COLUMN public.contract_templates.description IS '模板描述';
COMMENT ON COLUMN public.contract_templates.file_path IS '源模板文件路径';
COMMENT ON COLUMN public.contract_templates.file_format IS '文件格式';
COMMENT ON COLUMN public.contract_templates.is_featured IS '是否推荐模板';
COMMENT ON COLUMN public.contract_templates.pdf_file_path IS 'PDF预览文件路径';

COMMIT;
