/*
 * py_chanwalk_batch.pgc - py 채널별 집계 순회 (커서 배치, XA).
 *
 * Walks a channel-grouped cursor over the day's payouts, accumulating channel
 * count and grand total, inside ONE XA transaction.
 * Usage: py_chanwalk_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "py_chanwalk_batch.h"

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

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_ch[16];
    long h_cnt, h_amt;
    EXEC SQL END DECLARE SECTION;

    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    rec.channels = 0; rec.grand_total = 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 cwcur CURSOR FOR
        SELECT channel, count(*), coalesce(sum(amount),0)
        FROM py_payout WHERE biz_date = :h_bizdate GROUP BY channel ORDER BY channel;
    EXEC SQL OPEN cwcur;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "py_chanwalk_batch OPEN FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH cwcur INTO :h_ch, :h_cnt, :h_amt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE cwcur; fprintf(stderr, "py_chanwalk_batch FETCH FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
        rec.channels++; rec.grand_total += h_amt;
    }
    EXEC SQL CLOSE cwcur;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }

    strncpy(rec.biz_date, bizdate, sizeof(rec.biz_date)-1); rec.biz_date[sizeof(rec.biz_date)-1] = 0;
    printf(">>> py_chanwalk_batch COMMIT: date=%s channels=%ld grand_total=%ld\n",
           rec.biz_date, rec.channels, rec.grand_total);

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