/*
 * cm_svcacc_batch.pgc - cm 서비스별 로그 커서 누적/최대 산출 배치 (XA).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction; 서비스별(건수,log_id 합)을 커서로 순회하며 총건수/총합을 누적
 * 하고, C 에서 최대 그룹합(peak)을 if 로 갱신(행별 DML 없음); then tpcommit.
 * Usage: cm_svcacc_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "cm_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, peak = 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 ac CURSOR FOR
        SELECT svc_name, count(*), coalesce(sum(log_id),0) FROM cm_log
        WHERE biz_date = :h_bizdate GROUP BY svc_name;
    EXEC SQL OPEN ac;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH ac INTO :h_key, :h_cnt, :h_amt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE ac; tpabort(0); return 1; }
        tot_cnt += h_cnt; tot_amt += h_amt; groups++;
        if (h_amt > peak) peak = h_amt;
    }
    EXEC SQL CLOSE ac;

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

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