-- 실행 중인(STARTED) 배치 Job과 Step을 강제 종료
-- 주의: 실제로 실행 중인 프로세스를 종료하지는 않습니다.
-- DB 상태만 변경하므로, 애플리케이션을 먼저 중지한 후 사용하세요.

-- 1. 현재 실행 중인 Job 확인
SELECT
    '=== RUNNING JOBS ===' as status,
    JOB_EXECUTION_ID,
    JOB_INSTANCE_ID,
    START_TIME,
    STATUS,
    (SELECT JOB_NAME FROM BATCH_JOB_INSTANCE WHERE JOB_INSTANCE_ID = bje.JOB_INSTANCE_ID) as JOB_NAME
FROM BATCH_JOB_EXECUTION bje
WHERE STATUS IN ('STARTED', 'STARTING', 'STOPPING')
ORDER BY START_TIME DESC;

-- 2. 실행 중인 Step 확인
SELECT
    '=== RUNNING STEPS ===' as status,
    bse.STEP_EXECUTION_ID,
    bse.JOB_EXECUTION_ID,
    bse.STEP_NAME,
    bse.STATUS,
    bse.START_TIME
FROM BATCH_STEP_EXECUTION bse
WHERE STATUS IN ('STARTED', 'STARTING', 'STOPPING')
ORDER BY START_TIME DESC;

-- 3. 실행 중인 Step을 STOPPED로 변경
UPDATE BATCH_STEP_EXECUTION
SET
    STATUS = 'STOPPED',
    EXIT_CODE = 'STOPPED',
    EXIT_MESSAGE = 'Manually stopped - Original status: ' || STATUS,
    END_TIME = CURRENT_TIMESTAMP,
    LAST_UPDATED = CURRENT_TIMESTAMP
WHERE STATUS IN ('STARTED', 'STARTING', 'STOPPING');

-- 4. 실행 중인 Job을 STOPPED로 변경
UPDATE BATCH_JOB_EXECUTION
SET
    STATUS = 'STOPPED',
    EXIT_CODE = 'STOPPED',
    EXIT_MESSAGE = 'Manually stopped - Original status: ' || STATUS,
    END_TIME = CURRENT_TIMESTAMP,
    LAST_UPDATED = CURRENT_TIMESTAMP
WHERE STATUS IN ('STARTED', 'STARTING', 'STOPPING');

-- 5. 결과 확인
SELECT
    '=== AFTER STOP ===' as status,
    COUNT(*) as running_jobs
FROM BATCH_JOB_EXECUTION
WHERE STATUS IN ('STARTED', 'STARTING', 'STOPPING');

SELECT
    '=== STOPPED JOBS ===' as status,
    JOB_EXECUTION_ID,
    JOB_INSTANCE_ID,
    START_TIME,
    END_TIME,
    STATUS,
    EXIT_CODE
FROM BATCH_JOB_EXECUTION
WHERE STATUS = 'STOPPED'
ORDER BY JOB_EXECUTION_ID DESC
LIMIT 10;
