-- video_analysis_task 视频分析异步任务主表
CREATE TABLE IF NOT EXISTS video_analysis_task (
    id BIGSERIAL NOT NULL,
    tenant_id BIGINT NOT NULL DEFAULT 0,
    task_id VARCHAR(64) NOT NULL,
    callback_url VARCHAR(500) NOT NULL DEFAULT '',
    status VARCHAR(20) NOT NULL DEFAULT 'pending',
    total INT NOT NULL DEFAULT 0,
    success_count INT NOT NULL DEFAULT 0,
    failed_count INT NOT NULL DEFAULT 0,
    error_message TEXT,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    deleted_at TIMESTAMP WITH TIME ZONE,
    PRIMARY KEY (id)
);

COMMENT ON TABLE video_analysis_task IS '视频分析异步任务表';
COMMENT ON COLUMN video_analysis_task.task_id IS '任务唯一标识';
COMMENT ON COLUMN video_analysis_task.callback_url IS '回调地址';
COMMENT ON COLUMN video_analysis_task.status IS '任务状态:pending/processing/success/failed';
COMMENT ON COLUMN video_analysis_task.total IS '待分析视频总数';
COMMENT ON COLUMN video_analysis_task.success_count IS '成功数';
COMMENT ON COLUMN video_analysis_task.failed_count IS '失败数';
COMMENT ON COLUMN video_analysis_task.error_message IS '错误信息';
COMMENT ON COLUMN video_analysis_task.created_at IS '创建时间';
COMMENT ON COLUMN video_analysis_task.updated_at IS '更新时间';
COMMENT ON COLUMN video_analysis_task.deleted_at IS '删除时间(软删除)';

CREATE UNIQUE INDEX IF NOT EXISTS idx_video_analysis_task_task_id ON video_analysis_task(task_id);
CREATE INDEX IF NOT EXISTS idx_video_analysis_task_status ON video_analysis_task(status);
CREATE INDEX IF NOT EXISTS idx_video_analysis_task_created_at ON video_analysis_task(created_at);

-- video_analysis_task_detail 视频分析任务明细表（每视频一条）
CREATE TABLE IF NOT EXISTS video_analysis_task_detail (
    id BIGSERIAL NOT NULL,
    task_id VARCHAR(64) NOT NULL,
    tenant_id BIGINT NOT NULL DEFAULT 0,
    video_url TEXT NOT NULL,
    video_save_path TEXT NOT NULL DEFAULT '',
    status VARCHAR(20) NOT NULL DEFAULT 'pending',
    caption_result TEXT,
    fail_reason TEXT,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    PRIMARY KEY (id)
);

COMMENT ON TABLE video_analysis_task_detail IS '视频分析任务明细表';
COMMENT ON COLUMN video_analysis_task_detail.task_id IS '所属任务ID';
COMMENT ON COLUMN video_analysis_task_detail.tenant_id IS '租户ID';
COMMENT ON COLUMN video_analysis_task_detail.video_url IS '原始视频URL';
COMMENT ON COLUMN video_analysis_task_detail.video_save_path IS '视频本地保存路径(永久保留)';
COMMENT ON COLUMN video_analysis_task_detail.status IS '状态:pending/success/failed';
COMMENT ON COLUMN video_analysis_task_detail.caption_result IS 'Caption接口返回结果JSON';
COMMENT ON COLUMN video_analysis_task_detail.fail_reason IS '失败原因';
COMMENT ON COLUMN video_analysis_task_detail.created_at IS '创建时间';
COMMENT ON COLUMN video_analysis_task_detail.updated_at IS '更新时间';

CREATE INDEX IF NOT EXISTS idx_video_analysis_task_detail_task_id ON video_analysis_task_detail(task_id);
