/*
 * mm_mcc_reclass_batch.pgc - MCC 위험도 재분류 배치 (업종별 폐업률 기반 + XA).
 *
 * MCC 별 소속 가맹점의 폐업(DELETED) 비율로 위험도를 재산정한다:
 * 신위험도 = 1 + (폐업수 * 4 / 전체수), 1~5 범위. 기존 값과 다를 때만 UPDATE.
 * 전 구간 ONE global XA transaction.
 * host 변수는 전용 카피북 mm_mcc_reclass_cpy.h 를 EXEC SQL INCLUDE.
 * Usage: mm_mcc_reclass_batch
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>

int main(int argc, char **argv)
{
    long scanned = 0, changed = 0;
    (void)argc; (void)argv;

    EXEC SQL INCLUDE mm_mcc_reclass_cpy;

    if (tpinit(NULL) < 0) { fprintf(stderr, "tpinit FAIL: %s\n", tpstrerror(tperrno)); return 1; }
    if (tpopen() < 0)     { fprintf(stderr, "tpopen FAIL: %s\n", tpstrerror(tperrno)); return 1; }
    if (tpbegin(60, 0) < 0) { fprintf(stderr, "tpbegin FAIL: %s\n", tpstrerror(tperrno)); return 1; }

    EXEC SQL DECLARE mrc CURSOR FOR
        SELECT c.mcc, c.risk_level, count(me.merchant_id),
               coalesce(sum(CASE WHEN me.status = 'DELETED' THEN 1 ELSE 0 END), 0)
        FROM mm_mcc c
        JOIN mm_merchant_ext me ON me.mcc = c.mcc
        GROUP BY c.mcc, c.risk_level
        ORDER BY c.mcc;
    EXEC SQL OPEN mrc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH mrc INTO :b_mcc, :b_risk, :b_total, :b_closed;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE mrc; tpabort(0); return 1; }
        scanned++;
        if (b_total <= 0) continue;
        b_newrisk = 1 + (b_closed * 4) / b_total;
        if (b_newrisk > 5) b_newrisk = 5;
        if (b_newrisk == b_risk) continue;
        EXEC SQL UPDATE mm_mcc SET risk_level = :b_newrisk WHERE mcc = :b_mcc;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "UPDATE FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE mrc; tpabort(0); return 1; }
        changed++;
    }
    EXEC SQL CLOSE mrc;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mm_mcc_reclass_batch COMMIT: 점검 MCC=%ld 위험도 변경=%ld건\n", scanned, changed);

    tpclose(); tpterm();
    return 0;
}
