/*
 * st_merchroll_batch.pgc - 가맹점 정산 롤업 (XA 배치).
 * 가맹점별 매입/수수료/net 을 집계해 st_merch_settle 에 upsert.
 * ATMI 클라이언트: tpinit/tpopen 으로 ECPG XA RM 를 열고 tpbegin 으로 ONE global tx
 * 를 시작, EXEC SQL 수행 후 tpcommit 이 XA 2PC 를 구동. 사용법: st_merchroll_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "st_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];
    long h_cnt, h_gross, h_fee, h_net;
    char h_merch[64];
    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 st_merchroll_batch_c CURSOR FOR
        SELECT s.merchant_id, count(*), coalesce(sum(p.amount),0), coalesce(sum(p.fee),0), coalesce(sum(s.net),0)
        FROM settlement s JOIN purchase p ON p.purchase_id=s.purchase_id
        WHERE s.biz_date=:h_bizdate GROUP BY s.merchant_id ORDER BY s.merchant_id;
    EXEC SQL OPEN st_merchroll_batch_c;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH st_merchroll_batch_c 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 st_merchroll_batch_c; tpabort(0); return 1; }
        if (stdb_upsert_merch_settle(h_merch, bizdate, h_gross, h_fee, h_net, h_cnt) < 0) { EXEC SQL CLOSE st_merchroll_batch_c; tpabort(0); return 1; }
        rows++;
    }
    EXEC SQL CLOSE st_merchroll_batch_c;

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

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