-- 특정 JOB_EXECUTION_ID를 ABANDONED로 변경
-- 사용법: :job_execution_id 를 실제 ID로 변경 후 실행

-- 변수 설정 (PostgreSQL에서는 psql 변수 사용)
-- psql -v job_id=12345 -f mark-specific-job-as-abandoned.sql
-- 또는 아래 :job_execution_id 를 직접 숫자로 변경

-- 1. 해당 Job 상태 확인
SELECT
    '=== BEFORE UPDATE ===' as status,
    JOB_EXECUTION_ID,
    JOB_INSTANCE_ID,
    START_TIME,
    END_TIME,
    STATUS,
    EXIT_CODE,
    EXIT_MESSAGE
FROM BATCH_JOB_EXECUTION
WHERE JOB_EXECUTION_ID = :job_execution_id;

-- 2. 해당 Job의 Step들 상태 확인
SELECT
    '=== STEPS BEFORE UPDATE ===' as status,
    STEP_EXECUTION_ID,
    STEP_NAME,
    STATUS,
    EXIT_CODE
FROM BATCH_STEP_EXECUTION
WHERE JOB_EXECUTION_ID = :job_execution_id
ORDER BY STEP_EXECUTION_ID;

-- 3. Step을 ABANDONED로 변경
UPDATE BATCH_STEP_EXECUTION
SET
    STATUS = 'ABANDONED',
    EXIT_CODE = 'ABANDONED',
    EXIT_MESSAGE = 'Manually marked as ABANDONED - Original status: ' || STATUS,
    END_TIME = COALESCE(END_TIME, CURRENT_TIMESTAMP),
    LAST_UPDATED = CURRENT_TIMESTAMP
WHERE JOB_EXECUTION_ID = :job_execution_id
  AND STATUS IN ('FAILED', 'STARTED', 'STOPPING');

-- 4. Job을 ABANDONED로 변경
UPDATE BATCH_JOB_EXECUTION
SET
    STATUS = 'ABANDONED',
    EXIT_CODE = 'ABANDONED',
    EXIT_MESSAGE = 'Manually marked as ABANDONED - Original status: ' || STATUS,
    END_TIME = COALESCE(END_TIME, CURRENT_TIMESTAMP),
    LAST_UPDATED = CURRENT_TIMESTAMP
WHERE JOB_EXECUTION_ID = :job_execution_id
  AND STATUS IN ('FAILED', 'STARTED', 'STOPPING');

-- 5. 업데이트 결과 확인
SELECT
    '=== AFTER UPDATE ===' as status,
    JOB_EXECUTION_ID,
    JOB_INSTANCE_ID,
    START_TIME,
    END_TIME,
    STATUS,
    EXIT_CODE,
    EXIT_MESSAGE
FROM BATCH_JOB_EXECUTION
WHERE JOB_EXECUTION_ID = :job_execution_id;

SELECT
    '=== STEPS AFTER UPDATE ===' as status,
    STEP_EXECUTION_ID,
    STEP_NAME,
    STATUS,
    EXIT_CODE
FROM BATCH_STEP_EXECUTION
WHERE JOB_EXECUTION_ID = :job_execution_id
ORDER BY STEP_EXECUTION_ID;
