/*
 * au_month_limit_batch.pgc - au 월 한도 소진 카드 집계 배치 (단일 집계 + XA).
 *
 * Aggregates in ONE query how many active cards have burned >= 80% of their
 * daily limit and their total used amount, under one global XA transaction.
 * No cursor. Usage: au_month_limit_batch
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "au_dbio.h"
EXEC SQL INCLUDE au_month_limit_batch;

int main(int argc, char **argv)
{
    EXEC SQL BEGIN DECLARE SECTION;
    long h_cards = 0, h_used = 0;
    EXEC SQL END DECLARE SECTION;

    (void)argc; (void)argv;
    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(*), coalesce(sum(used_amount),0)
        INTO :h_cards, :h_used
        FROM card_limit
        WHERE daily_limit > 0 AND used_amount * 100 >= daily_limit * 80;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "SELECT FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> au_month_limit_batch COMMIT: cards_over80=%ld used_total=%ld\n", h_cards, h_used);

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