/*
  Warnings:

  - The values [COMPLETED] on the enum `InstanceStatus` will be removed. If these variants are still used in the database, this will fail.

*/

-- 第一步：添加临时列存储原始状态
ALTER TABLE "corp_approval"."approval_instances" ADD COLUMN IF NOT EXISTS "temp_old_status" TEXT;
UPDATE "corp_approval"."approval_instances" 
SET "temp_old_status" = "status"::text;

-- 第二步：将所有 COMPLETED 状态临时改为 RUNNING（因为新枚举中没有COMPLETED）
UPDATE "corp_approval"."approval_instances" 
SET "status" = 'RUNNING'::"corp_approval"."InstanceStatus"
WHERE "status" = 'COMPLETED'::"corp_approval"."InstanceStatus";

-- 第三步：执行枚举类型更新
BEGIN;
CREATE TYPE "corp_approval"."InstanceStatus_new" AS ENUM ('RUNNING', 'SUSPENDED', 'APPROVED', 'REJECTED', 'WITHDRAWN', 'TERMINATED', 'FAILED');
ALTER TABLE "corp_approval"."approval_instances" ALTER COLUMN "status" DROP DEFAULT;
ALTER TABLE "corp_approval"."approval_instances" ALTER COLUMN "status" TYPE "corp_approval"."InstanceStatus_new" USING ("status"::text::"corp_approval"."InstanceStatus_new");
ALTER TYPE "corp_approval"."InstanceStatus" RENAME TO "InstanceStatus_old";
ALTER TYPE "corp_approval"."InstanceStatus_new" RENAME TO "InstanceStatus";
DROP TYPE "corp_approval"."InstanceStatus_old";
ALTER TABLE "corp_approval"."approval_instances" ALTER COLUMN "status" SET DEFAULT 'RUNNING';
COMMIT;

-- 第四步：根据原始状态和 end_reason 设置正确的新状态
UPDATE "corp_approval"."approval_instances"
SET "status" = 
  CASE 
    -- 原来是 COMPLETED 的，根据 end_reason 智能迁移
    WHEN "temp_old_status" = 'COMPLETED' AND "end_reason" = 'REJECTED' THEN 'REJECTED'::"corp_approval"."InstanceStatus"
    WHEN "temp_old_status" = 'COMPLETED' AND "end_reason" = 'WITHDRAWN' THEN 'WITHDRAWN'::"corp_approval"."InstanceStatus"
    WHEN "temp_old_status" = 'COMPLETED' AND "end_reason" LIKE 'ADMIN_%' THEN 'TERMINATED'::"corp_approval"."InstanceStatus"
    WHEN "temp_old_status" = 'COMPLETED' THEN 'APPROVED'::"corp_approval"."InstanceStatus"
    -- 其他状态保持不变
    ELSE "status"
  END
WHERE "temp_old_status" = 'COMPLETED';

-- 第五步：清理临时列
ALTER TABLE "corp_approval"."approval_instances" DROP COLUMN IF EXISTS "temp_old_status";

-- AlterTable
ALTER TABLE "corp_approval"."approval_instances" ALTER COLUMN "title" SET DATA TYPE TEXT;

-- CreateIndex
CREATE INDEX IF NOT EXISTS "approval_task_logs_target_user_id_idx" ON "corp_approval"."approval_task_logs"("target_user_id");

-- AddForeignKey
DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM pg_constraint 
    WHERE conname = 'approval_task_logs_target_user_id_fkey'
  ) THEN
    ALTER TABLE "corp_approval"."approval_task_logs" 
    ADD CONSTRAINT "approval_task_logs_target_user_id_fkey" 
    FOREIGN KEY ("target_user_id") 
    REFERENCES "platform_iam"."users"("id") 
    ON DELETE SET NULL 
    ON UPDATE CASCADE;
  END IF;
END $$;


