/*
 * au_brand_mix_batch.pgc - au 브랜드별 승인 믹스 집계 배치 (substr GROUP BY 커서 + XA).
 *
 * Groups the day's authorizations by card brand (leading digit) reporting count
 * and amount, and accumulates the top brand by amount, under one global XA
 * transaction. Read-only report. Usage: au_brand_mix_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "au_dbio.h"
EXEC SQL INCLUDE au_brand_mix_batch;

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    long total = 0, top_amt = 0;
    char top_lead[4] = "";
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_lead[4];
    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;

    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 bmx CURSOR FOR
        SELECT substr(card_no, 1, 1), count(*), coalesce(sum(amount),0)
        FROM au_authorization
        WHERE biz_date = :h_bizdate AND status IN ('A','M','S')
        GROUP BY substr(card_no, 1, 1) ORDER BY coalesce(sum(amount),0) DESC;
    EXEC SQL OPEN bmx;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH bmx INTO :h_lead, :h_cnt, :h_amt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d]\n", sqlca.sqlcode); EXEC SQL CLOSE bmx; tpabort(0); return 1; }
        total += h_cnt;
        if (h_amt > top_amt) { top_amt = h_amt; strncpy(top_lead, h_lead, sizeof(top_lead)-1); }
        printf("    brand_lead=%s cnt=%ld amt=%ld\n", h_lead, h_cnt, h_amt);
    }
    EXEC SQL CLOSE bmx;

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

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