-- 실패한 배치 Job 조회 및 분석

-- 1. 실패한 Job 목록 (최근 50개)
SELECT
    '=== FAILED JOBS (Recent 50) ===' as category,
    bje.JOB_EXECUTION_ID,
    bji.JOB_NAME,
    bje.START_TIME,
    bje.END_TIME,
    bje.STATUS,
    bje.EXIT_CODE,
    LEFT(bje.EXIT_MESSAGE, 100) as EXIT_MESSAGE_SHORT,
    -- Job Parameters 표시
    (SELECT string_agg(PARAMETER_NAME || '=' || PARAMETER_VALUE, ', ')
     FROM BATCH_JOB_EXECUTION_PARAMS
     WHERE JOB_EXECUTION_ID = bje.JOB_EXECUTION_ID
     AND IDENTIFYING = 'Y') as PARAMETERS
FROM BATCH_JOB_EXECUTION bje
JOIN BATCH_JOB_INSTANCE bji ON bje.JOB_INSTANCE_ID = bji.JOB_INSTANCE_ID
WHERE bje.STATUS = 'FAILED'
ORDER BY bje.JOB_EXECUTION_ID DESC
LIMIT 50;

-- 2. 실패한 Step 상세 정보
SELECT
    '=== FAILED STEPS ===' as category,
    bse.STEP_EXECUTION_ID,
    bse.JOB_EXECUTION_ID,
    bji.JOB_NAME,
    bse.STEP_NAME,
    bse.STATUS,
    bse.READ_COUNT,
    bse.WRITE_COUNT,
    bse.COMMIT_COUNT,
    bse.ROLLBACK_COUNT,
    bse.READ_SKIP_COUNT,
    bse.PROCESS_SKIP_COUNT,
    bse.WRITE_SKIP_COUNT,
    LEFT(bse.EXIT_MESSAGE, 100) as EXIT_MESSAGE_SHORT
FROM BATCH_STEP_EXECUTION bse
JOIN BATCH_JOB_EXECUTION bje ON bse.JOB_EXECUTION_ID = bje.JOB_EXECUTION_ID
JOIN BATCH_JOB_INSTANCE bji ON bje.JOB_INSTANCE_ID = bji.JOB_INSTANCE_ID
WHERE bse.STATUS = 'FAILED'
ORDER BY bse.STEP_EXECUTION_ID DESC
LIMIT 50;

-- 3. Job 타입별 실패 통계
SELECT
    '=== FAILURE STATISTICS BY JOB ===' as category,
    bji.JOB_NAME,
    COUNT(*) as FAILED_COUNT,
    MAX(bje.END_TIME) as LAST_FAILURE_TIME
FROM BATCH_JOB_EXECUTION bje
JOIN BATCH_JOB_INSTANCE bji ON bje.JOB_INSTANCE_ID = bji.JOB_INSTANCE_ID
WHERE bje.STATUS = 'FAILED'
GROUP BY bji.JOB_NAME
ORDER BY FAILED_COUNT DESC;

-- 4. Step별 실패 통계
SELECT
    '=== FAILURE STATISTICS BY STEP ===' as category,
    STEP_NAME,
    COUNT(*) as FAILED_COUNT,
    MAX(END_TIME) as LAST_FAILURE_TIME
FROM BATCH_STEP_EXECUTION
WHERE STATUS = 'FAILED'
GROUP BY STEP_NAME
ORDER BY FAILED_COUNT DESC;

-- 5. 최근 24시간 실패 현황
SELECT
    '=== LAST 24 HOURS ===' as category,
    COUNT(*) as FAILED_JOBS_24H
FROM BATCH_JOB_EXECUTION
WHERE STATUS = 'FAILED'
  AND START_TIME >= CURRENT_TIMESTAMP - INTERVAL '24 hours';

-- 6. 전체 상태 요약
SELECT
    '=== STATUS SUMMARY ===' as category,
    STATUS,
    COUNT(*) as COUNT
FROM BATCH_JOB_EXECUTION
GROUP BY STATUS
ORDER BY COUNT DESC;
