-- 文件/任务处理进度（方案 B：真实百分比 + 阶段）
-- 在 PostgreSQL 上执行本脚本后再部署新版后端与前端。

-- 知识库文件
ALTER TABLE public.knowledge_base_file
    ADD COLUMN IF NOT EXISTS progress_percent smallint NOT NULL DEFAULT 0,
    ADD COLUMN IF NOT EXISTS processing_stage varchar(50) NULL;

ALTER TABLE public.knowledge_base_file
    DROP CONSTRAINT IF EXISTS ck_kb_file_progress_percent;
ALTER TABLE public.knowledge_base_file
    ADD CONSTRAINT ck_kb_file_progress_percent
    CHECK (progress_percent >= 0 AND progress_percent <= 100);

COMMENT ON COLUMN public.knowledge_base_file.progress_percent IS '处理进度 0-100';
COMMENT ON COLUMN public.knowledge_base_file.processing_stage IS 'processing 阶段: uploading/parsing/ocr/embedding/summarizing/completed 等';

-- 聊天文件
ALTER TABLE public.chat_thread_file
    ADD COLUMN IF NOT EXISTS progress_percent smallint NOT NULL DEFAULT 0,
    ADD COLUMN IF NOT EXISTS processing_stage varchar(50) NULL;

ALTER TABLE public.chat_thread_file
    DROP CONSTRAINT IF EXISTS ck_chat_thread_file_progress_percent;
ALTER TABLE public.chat_thread_file
    ADD CONSTRAINT ck_chat_thread_file_progress_percent
    CHECK (progress_percent >= 0 AND progress_percent <= 100);

COMMENT ON COLUMN public.chat_thread_file.progress_percent IS '处理进度 0-100';
COMMENT ON COLUMN public.chat_thread_file.processing_stage IS 'processing 阶段';

-- 知识图谱
ALTER TABLE public.graphs
    ADD COLUMN IF NOT EXISTS progress_percent smallint NOT NULL DEFAULT 0,
    ADD COLUMN IF NOT EXISTS processing_stage varchar(50) NULL;

ALTER TABLE public.graphs
    DROP CONSTRAINT IF EXISTS ck_graphs_progress_percent;
ALTER TABLE public.graphs
    ADD CONSTRAINT ck_graphs_progress_percent
    CHECK (progress_percent >= 0 AND progress_percent <= 100);

COMMENT ON COLUMN public.graphs.progress_percent IS '构建进度 0-100';
COMMENT ON COLUMN public.graphs.processing_stage IS '构建阶段: extracting/indexing/completed 等';

-- 知识加工任务（可选：与文件上传同属长任务）
ALTER TABLE public.knowledge_processing_task
    ADD COLUMN IF NOT EXISTS progress_percent smallint NOT NULL DEFAULT 0,
    ADD COLUMN IF NOT EXISTS processing_stage varchar(50) NULL;

ALTER TABLE public.knowledge_processing_task
    DROP CONSTRAINT IF EXISTS ck_kb_processing_task_progress_percent;
ALTER TABLE public.knowledge_processing_task
    ADD CONSTRAINT ck_kb_processing_task_progress_percent
    CHECK (progress_percent >= 0 AND progress_percent <= 100);

COMMENT ON COLUMN public.knowledge_processing_task.progress_percent IS '任务进度 0-100';
COMMENT ON COLUMN public.knowledge_processing_task.processing_stage IS '任务阶段';
