-- 取消图生视频任务: img2vid_1957126e9dbd46e2
-- 1. 更新任务队列状态为 CANCELLED
UPDATE task_queue 
SET status = 'CANCELLED', 
    error_message = '用户取消了任务',
    updated_at = NOW()
WHERE task_id = 'img2vid_1957126e9dbd46e2';

-- 2. 更新图生视频任务状态为 CANCELLED
UPDATE image_to_video_tasks 
SET status = 'CANCELLED',
    error_message = '用户取消了任务',
    updated_at = NOW()
WHERE task_id = 'img2vid_1957126e9dbd46e2';

-- 3. 更新用户积分（减少冻结积分）
-- 注意：只减少 frozen_points，不增加 points（总积分不变）
UPDATE users 
SET frozen_points = frozen_points - (
    SELECT COALESCE(freeze_points, 0) 
    FROM points_freeze_records 
    WHERE task_id = 'img2vid_1957126e9dbd46e2' 
      AND status = 'FROZEN' 
    LIMIT 1
),
    updated_at = NOW()
WHERE username = (
    SELECT username 
    FROM task_queue 
    WHERE task_id = 'img2vid_1957126e9dbd46e2' 
    LIMIT 1
)
AND EXISTS (
    SELECT 1 
    FROM points_freeze_records 
    WHERE task_id = 'img2vid_1957126e9dbd46e2' 
      AND status = 'FROZEN'
);

-- 4. 返还冻结的积分（将冻结记录状态改为 RETURNED）
UPDATE points_freeze_records 
SET status = 'RETURNED',
    updated_at = NOW()
WHERE task_id = 'img2vid_1957126e9dbd46e2' 
  AND status = 'FROZEN';

-- 5. 查询任务信息（用于确认）
SELECT 
    tq.task_id,
    tq.status as queue_status,
    tq.username,
    tq.error_message,
    itvt.status as task_status,
    pfr.freeze_points,
    pfr.status as freeze_status
FROM task_queue tq
LEFT JOIN image_to_video_tasks itvt ON tq.task_id = itvt.task_id
LEFT JOIN points_freeze_records pfr ON tq.task_id = pfr.task_id
WHERE tq.task_id = 'img2vid_1957126e9dbd46e2';

-- 查询结果
SELECT '任务已取消' as result;


