/*
 * mm_risk_score_batch.pgc - 전 가맹점 리스크 점수 재산정 배치 (JOIN 커서 + C 산정 + XA).
 *
 * 가맹점 등급/상태/MCC 위험도를 조합해 리스크 점수를 산출하고 밴드(LOW/MID/HIGH)를
 * RISK 이력으로 적재한다(온라인 MM_RISK_SCORE와 동일 공식). ONE global XA transaction.
 * host 변수는 mm_risk_score_cpy.h 를 EXEC SQL INCLUDE.
 * Usage: mm_risk_score_batch
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "mm_dbio.h"

int main(int argc, char **argv)
{
    long score;
    const char *band;
    char memo[48];
    (void)argc; (void)argv;
    EXEC SQL INCLUDE mm_risk_score_cpy;
    b_scored = 0;

    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 rsc CURSOR FOR
        SELECT me.merchant_id, me.grade, me.status, coalesce(m.risk_level, 1)
        FROM mm_merchant_ext me
        LEFT JOIN mm_mcc m ON m.mcc = me.mcc
        WHERE me.status <> 'DELETED'
        ORDER BY me.merchant_id;
    EXEC SQL OPEN rsc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH rsc INTO :b_merch, :b_grade, :b_stat, :b_risk;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE rsc; tpabort(0); return 1; }
        score = b_risk * 20;
        if (b_grade[0] == 'C') score += 20;
        else if (b_grade[0] == 'B') score += 10;
        if (strcmp(b_stat, "ACTIVE") != 0) score += 15;
        if (score > 100) score = 100;
        band = (score >= 70) ? "HIGH" : (score >= 40) ? "MID" : "LOW";
        snprintf(memo, sizeof(memo), "리스크 %ld", score);
        if (mmdb_insert_merch_hist(b_merch, "RISK", "", (char *)band, memo) < 0) {
            EXEC SQL CLOSE rsc; tpabort(0); return 1;
        }
        b_scored++;
    }
    EXEC SQL CLOSE rsc;

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

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