/*
 * au_mcc_risk_batch.pgc - au 고위험 업종 매입 집계 배치 (GROUP BY HAVING 커서 + XA).
 *
 * Reports categories whose day's purchase volume exceeds 3,000,000 (HAVING),
 * scanning count/sum/max per category under one global XA transaction. Read-only
 * report. Usage: au_mcc_risk_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "au_dbio.h"
EXEC SQL INCLUDE au_mcc_risk_batch;

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    long groups = 0, grand = 0;
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_cat[32];
    long h_cnt, h_sum, h_max;
    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 mrk CURSOR FOR
        SELECT category, count(*), coalesce(sum(amount),0), coalesce(max(amount),0)
        FROM purchase WHERE biz_date = :h_bizdate
        GROUP BY category HAVING coalesce(sum(amount),0) > 3000000
        ORDER BY coalesce(sum(amount),0) DESC;
    EXEC SQL OPEN mrk;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH mrk INTO :h_cat, :h_cnt, :h_sum, :h_max;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d]\n", sqlca.sqlcode); EXEC SQL CLOSE mrk; tpabort(0); return 1; }
        groups++;
        grand += h_sum;
        printf("    risk category=%s cnt=%ld sum=%ld max=%ld\n", h_cat, h_cnt, h_sum, h_max);
    }
    EXEC SQL CLOSE mrk;

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

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