/*
 * mg_chanacc_batch.pgc - mg 채널별 전문 커서 누적 배치 (XA).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction; 채널별(건수, 금액합)을 커서로 순회하며 총건수/총금액을 누적만
 * 한다(행별 DML/조건분기 없음); then tpcommit drives XA 2PC.
 * Usage: mg_chanacc_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "mg_dbio.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_key[32];
    long h_cnt = 0, h_amt = 0;
    EXEC SQL END DECLARE SECTION;
    long tot_cnt = 0, tot_amt = 0, groups = 0;

    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 cc CURSOR FOR
        SELECT channel, count(*), coalesce(sum(amount),0) FROM mg_msg_log
        WHERE biz_date = :h_bizdate GROUP BY channel;
    EXEC SQL OPEN cc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH cc INTO :h_key, :h_cnt, :h_amt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE cc; tpabort(0); return 1; }
        tot_cnt += h_cnt; tot_amt += h_amt; groups++;
    }
    EXEC SQL CLOSE cc;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mg_chanacc_batch COMMIT: bizdate=%s channels=%ld rows=%ld amount=%ld\n", bizdate, groups, tot_cnt, tot_amt);

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