-- 创建OCR结果表 (PostgreSQL语法)
CREATE TABLE IF NOT EXISTS t_ocr_result (
    id BIGSERIAL PRIMARY KEY,
    file_id BIGINT NOT NULL,
    project_id VARCHAR(64) NOT NULL,
    supplier_id VARCHAR(64),
    ocr_task_id VARCHAR(100),
    status VARCHAR(32) NOT NULL DEFAULT 'processing',
    recognized_text TEXT,
    download_url TEXT,
    download_file_name VARCHAR(512),
    processed_pages INTEGER,
    total_pages INTEGER,
    error_message TEXT,
    start_time TIMESTAMP,
    end_time TIMESTAMP,
    create_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    update_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,

    -- 外键约束
    CONSTRAINT fk_ocr_file FOREIGN KEY (file_id) REFERENCES t_file(id) ON DELETE CASCADE
);

-- 创建索引
CREATE INDEX IF NOT EXISTS idx_ocr_file_id ON t_ocr_result(file_id);
CREATE INDEX IF NOT EXISTS idx_ocr_project_id ON t_ocr_result(project_id);
CREATE INDEX IF NOT EXISTS idx_ocr_supplier_id ON t_ocr_result(supplier_id);
CREATE INDEX IF NOT EXISTS idx_ocr_status ON t_ocr_result(status);
CREATE INDEX IF NOT EXISTS idx_ocr_create_time ON t_ocr_result(create_time);

-- 创建更新时间触发器函数
CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
    NEW.update_time = CURRENT_TIMESTAMP;
    RETURN NEW;
END;
$$ language 'plpgsql';

-- 创建触发器
CREATE TRIGGER update_ocr_result_updated_at
    BEFORE UPDATE ON t_ocr_result
    FOR EACH ROW
    EXECUTE FUNCTION update_updated_at_column();

-- 添加注释 (PostgreSQL方式)
COMMENT ON TABLE t_ocr_result IS 'OCR识别结果表';
COMMENT ON COLUMN t_ocr_result.file_id IS '文件ID，关联t_file表';
COMMENT ON COLUMN t_ocr_result.project_id IS '项目ID';
COMMENT ON COLUMN t_ocr_result.supplier_id IS '供应商ID';
COMMENT ON COLUMN t_ocr_result.ocr_task_id IS 'OCR任务ID';
COMMENT ON COLUMN t_ocr_result.status IS '识别状态（processing-处理中, success-成功, failed-失败）';
COMMENT ON COLUMN t_ocr_result.recognized_text IS '识别文本内容';
COMMENT ON COLUMN t_ocr_result.download_url IS '下载链接（OCR结果文件下载链接）';
COMMENT ON COLUMN t_ocr_result.download_file_name IS '下载文件名';
COMMENT ON COLUMN t_ocr_result.processed_pages IS '处理页数';
COMMENT ON COLUMN t_ocr_result.total_pages IS '总页数';
COMMENT ON COLUMN t_ocr_result.error_message IS '错误信息';
COMMENT ON COLUMN t_ocr_result.start_time IS '开始时间';
COMMENT ON COLUMN t_ocr_result.end_time IS '完成时间';
COMMENT ON COLUMN t_ocr_result.create_time IS '创建时间';
COMMENT ON COLUMN t_ocr_result.update_time IS '更新时间';
