/*
 * mm_risk_rollup_batch.pgc - mm MCC 위험도 재산정 배치 (커서 + 가맹점수 기반 UPDATE + XA).
 *
 * mm_mcc 를 커서로 훑어 각 MCC 를 쓰는 가맹점 수를 세고, 그 규모에 따라 risk_level 을
 * 재산정(UPDATE)한다. 규모가 클수록 높은 위험도. 전 구간 ONE global XA transaction.
 * host 변수는 전용 카피북 mm_risk_rollup_cpy.h 를 EXEC SQL INCLUDE.
 * Usage: mm_risk_rollup_batch
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>

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

    EXEC SQL INCLUDE mm_risk_rollup_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 mrr CURSOR FOR SELECT mcc FROM mm_mcc ORDER BY mcc;
    EXEC SQL OPEN mrr;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH mrr INTO :k_mcc;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE mrr; tpabort(0); return 1; }
        EXEC SQL SELECT count(*) INTO :k_merch FROM mm_merchant_ext WHERE mcc = :k_mcc;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE mrr; tpabort(0); return 1; }
        k_level = (k_merch >= 100) ? 3 : (k_merch >= 10) ? 2 : 1;
        EXEC SQL UPDATE mm_mcc SET risk_level = :k_level WHERE mcc = :k_mcc;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "UPDATE FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE mrr; tpabort(0); return 1; }
        rolled++;
    }
    EXEC SQL CLOSE mrr;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mm_risk_rollup_batch COMMIT: 재산정=%ld건\n", rolled);

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