/*
 * ac_merchsum_batch.pgc - ac 가맹점 일집계 배치 (커서 + XA).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction, an EXEC SQL cursor aggregates purchase rows per merchant for a
 * biz_date and upserts merchant_summary (via the linked dbio lib), then tpcommit
 * drives XA 2PC. Usage: ac_merchsum_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "ac_dbio.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    long rows = 0;

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    char h_merch[64];
    long h_cnt, h_gross, h_fee, h_net;
    EXEC SQL END DECLARE SECTION;

    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 msc CURSOR FOR
        SELECT merchant_id, count(*), coalesce(sum(amount),0),
               coalesce(sum(fee),0), coalesce(sum(net),0)
        FROM purchase WHERE biz_date = :h_bizdate
        GROUP BY merchant_id ORDER BY merchant_id;
    EXEC SQL OPEN msc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH msc INTO :h_merch, :h_cnt, :h_gross, :h_fee, :h_net;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE msc; tpabort(0); return 1; }
        if (acdb_upsert_merch_sum(h_merch, bizdate, h_gross, h_fee, h_net, h_cnt) < 0) {
            EXEC SQL CLOSE msc; tpabort(0); return 1;
        }
        rows++;
    }
    EXEC SQL CLOSE msc;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> ac_merchsum_batch COMMIT: bizdate=%s merchants=%ld\n", bizdate, rows);

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