-- 回滚提交未知状态约束；已转换的任务状态不会反向推断。
ALTER TABLE drama_parse_tasks DROP CONSTRAINT drama_parse_tasks_status_check;
ALTER TABLE drama_parse_tasks
    ADD CONSTRAINT drama_parse_tasks_status_check
    CHECK (status IN ('queued', 'running', 'retry_wait', 'submit_unknown', 'succeeded', 'failed', 'cancel_requested', 'cancelled'));

ALTER TABLE generation_tasks DROP CONSTRAINT generation_tasks_status_check;
ALTER TABLE generation_tasks
    ADD CONSTRAINT generation_tasks_status_check
    CHECK (status IN ('pending_submission', 'submitting', 'submit_unknown', 'submitted', 'processing', 'result_ready', 'downloading', 'succeeded', 'failed', 'cancel_requested', 'cancelled'));

DROP INDEX idx_drama_parse_tasks_recovery;
CREATE INDEX idx_drama_parse_tasks_recovery
    ON drama_parse_tasks(status, lease_until)
    WHERE status IN ('queued', 'running', 'retry_wait', 'submit_unknown');

DROP INDEX uq_drama_episode_active_parse;
CREATE UNIQUE INDEX uq_drama_episode_active_parse
    ON drama_parse_tasks(episode_id)
    WHERE status IN ('queued', 'running', 'retry_wait', 'submit_unknown', 'cancel_requested');

DROP INDEX uq_script_analysis_active_task;
CREATE UNIQUE INDEX uq_script_analysis_active_task
    ON generation_tasks(script_analysis_id)
    WHERE script_analysis_id IS NOT NULL
      AND status IN ('pending_submission', 'submitting', 'submit_unknown', 'submitted', 'processing', 'result_ready', 'downloading', 'cancel_requested');
