/*
 * mg_mtiroll_batch.pgc - mg 전문유형(MTI)별 금액/건수 롤업 배치 (커서 + XA).
 *
 * 당일 전문을 MTI 로 그룹핑해 유형별 건수/금액합을 커서로 훑으며 총계를 누적하고,
 * 금액합이 가장 큰 유형을 찾아낸다 (전문 통계 유형별 세분의 일배치판).
 * Usage: mg_mtiroll_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "mg_mtiroll_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_mti[8];
    long h_cnt, h_amt;
    EXEC SQL END DECLARE SECTION;
    mg_mtiroll_rec_t rec;
    memset(&rec, 0, sizeof(rec));

    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 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 mrc CURSOR FOR
        SELECT mti, count(*), coalesce(sum(amount),0)
        FROM mg_msg_log WHERE biz_date = :h_bizdate
        GROUP BY mti ORDER BY mti;
    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 :h_mti, :h_cnt, :h_amt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE mrc; tpabort(0); return 1; }
        rec.groups++;
        rec.total_cnt += h_cnt;
        rec.total_amt += h_amt;
        if (h_amt > rec.top_amt) rec.top_amt = h_amt;
    }
    EXEC SQL CLOSE mrc;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mg_mtiroll_batch COMMIT: bizdate=%s 유형수=%ld 총건=%ld 총금액=%ld 최대유형금액=%ld\n",
           bizdate, rec.groups, rec.total_cnt, rec.total_amt, rec.top_amt);

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