/*
 * mm_mcc_risk_cursor_dbio.pgc - mm 모듈 DB 접근 함수 (mm_mcc_risk_cursor_dbio), archived into libmmdbio.a.
 * MCC 위험도 가맹점수 가중 합 (cursor + 누적).
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 */
#include <string.h>
#include <userlog.h>
#include "mm_mcc_risk_cursor_dbio.h"

/* MCC 를 커서로 훑어 각 MCC 의 가맹점 수 x risk_level 을 누적. */
long mmdb_mcc_weighted_risk(void)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_mcc[8];
    long h_risk, h_merch;
    EXEC SQL END DECLARE SECTION;
    long total = 0;
    EXEC SQL DECLARE mrc CURSOR FOR
        SELECT mcc, risk_level FROM mm_mcc ORDER BY mcc;
    EXEC SQL OPEN mrc;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH mrc INTO :h_mcc, :h_risk;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE mrc; return -1; }
        EXEC SQL SELECT count(*) INTO :h_merch FROM mm_merchant_ext WHERE mcc = :h_mcc;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE mrc; return -1; }
        total += h_risk * h_merch;
    }
    EXEC SQL CLOSE mrc;
    return total;
}
