/*
 * py_merchsum_batch.pgc - py 가맹점 지급 집계 (커서 + dbio upsert 배치, XA).
 *
 * Cursors the day's paid(P) payouts and rolls a per-merchant summary via the
 * dbio upsert, under ONE XA transaction. Usage: py_merchsum_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "py_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], h_merch[64];
    long h_pay, 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 pymsc CURSOR FOR
        SELECT payout_id, merchant_id, net FROM py_payout
        WHERE biz_date = :h_bizdate AND status = 'P'
        ORDER BY payout_id;
    EXEC SQL OPEN pymsc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH pymsc INTO :h_pay, :h_merch, :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 pymsc; tpabort(0); return 1; }
        if (pydb_upsert_summary(h_merch, bizdate, 1, h_net) < 0) { EXEC SQL CLOSE pymsc; tpabort(0); return 1; }
        rows++;
    }
    EXEC SQL CLOSE pymsc;

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

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