/*
 * ac_amountband_batch.pgc - ac 매입 금액대 분포 배치 (CASE 버킷 + XA).
 *
 * ATMI client: one global transaction; a single CASE-bucketed aggregate splits
 * the day's purchases into three amount bands. The C helper mirrors the band
 * thresholds for reporting. tpcommit drives XA 2PC.
 * Usage: ac_amountband_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "ac_amountband_batch.h"

/* 금액을 3구간으로 분류. */
int acb_band_classify(long amount)
{
    if (amount < 50000L) return 0;
    if (amount < 500000L) return 1;
    return 2;
}

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

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_lo = 0, h_mid = 0, h_hi = 0;
    EXEC SQL END DECLARE SECTION;

    memset(&ctx, 0, sizeof(ctx));
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    strncpy(ctx.biz_date, bizdate, sizeof(ctx.biz_date)-1);

    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 SELECT
        count(*) FILTER (WHERE amount < 50000),
        count(*) FILTER (WHERE amount >= 50000 AND amount < 500000),
        count(*) FILTER (WHERE amount >= 500000)
        INTO :h_lo, :h_mid, :h_hi
        FROM purchase WHERE biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "ac_amountband_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    ctx.band_lo = h_lo;
    ctx.band_mid = h_mid;
    ctx.band_hi = h_hi;
    (void)acb_band_classify(ctx.band_hi);

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> ac_amountband_batch COMMIT: bizdate=%s lo=%ld mid=%ld hi=%ld\n",
           ctx.biz_date, ctx.band_lo, ctx.band_mid, ctx.band_hi);

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