/*
 * au_topcard_batch.pgc - au 최고 지출 카드 배치 (window + XA).
 *
 * ATMI client: one global transaction; a windowed subquery ranks card spend and
 * picks the rn=1 card. tpcommit drives XA 2PC. Usage: au_topcard_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "au_topcard_batch.h"

/* 지출액이 양수면 유효한 결과로 간주. */
int aub_topcard_valid(long spend)
{
    return (spend > 0) ? 1 : 0;
}

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

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_card[24];
    long h_spend = 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(h_card, "NONE", sizeof(h_card)-1); h_card[sizeof(h_card)-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 card_no, spend FROM (
        SELECT card_no, sum(amount) AS spend,
               row_number() OVER (ORDER BY sum(amount) DESC) AS rn
        FROM au_authorization WHERE biz_date = :h_bizdate
        GROUP BY card_no) t WHERE t.rn = 1;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "au_topcard_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    if (sqlca.sqlcode != 100) {
        EXEC SQL SELECT card_no, spend INTO :h_card, :h_spend FROM (
            SELECT card_no, sum(amount) AS spend,
                   row_number() OVER (ORDER BY sum(amount) DESC) AS rn
            FROM au_authorization WHERE biz_date = :h_bizdate
            GROUP BY card_no) t WHERE t.rn = 1;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "au_topcard_batch FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    }

    strncpy(ctx.top_card, h_card, sizeof(ctx.top_card)-1);
    ctx.top_spend = h_spend;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> au_topcard_batch COMMIT: bizdate=%s top_card=%s spend=%ld valid=%d\n",
           ctx.biz_date, ctx.top_card, ctx.top_spend, aub_topcard_valid(ctx.top_spend));

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