/*
 * au_channel_stat_batch.pgc - au 채널별 매입 집계 배치 (GROUP BY 커서 + XA).
 *
 * Reports per-channel count / sum / average purchase amount for a business day,
 * scanning a GROUP BY cursor under one global XA transaction. Read-only report.
 * Usage: au_channel_stat_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "au_dbio.h"
EXEC SQL INCLUDE au_channel_stat_batch;

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    long chans = 0, total = 0;
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_chan[16];
    long h_cnt, h_sum, h_avg;
    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 cstb CURSOR FOR
        SELECT channel, count(*), coalesce(sum(amount),0),
               CAST(coalesce(avg(amount),0) AS bigint)
        FROM purchase WHERE biz_date = :h_bizdate
        GROUP BY channel ORDER BY count(*) DESC;
    EXEC SQL OPEN cstb;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH cstb INTO :h_chan, :h_cnt, :h_sum, :h_avg;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d]\n", sqlca.sqlcode); EXEC SQL CLOSE cstb; tpabort(0); return 1; }
        chans++;
        total += h_cnt;
        printf("    channel=%s cnt=%ld sum=%ld avg=%ld\n", h_chan, h_cnt, h_sum, h_avg);
    }
    EXEC SQL CLOSE cstb;

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

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