/*
 * au_exhaust_alert_batch.pgc - au 한도 소진 경보 로그 배치 (커서 + userlog + XA).
 *
 * Cursor-scans cards that have burned >= 90% of their daily limit and emits a
 * userlog alert for each, counting alerts, under one global XA transaction.
 * No dbio writes. Usage: au_exhaust_alert_batch
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "au_dbio.h"
EXEC SQL INCLUDE au_exhaust_alert_batch;
#include <userlog.h>

int main(int argc, char **argv)
{
    long alerts = 0;
    EXEC SQL BEGIN DECLARE SECTION;
    char h_card[24];
    long h_bps;
    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 DECLARE exa CURSOR FOR
        SELECT card_no, used_amount * 10000 / daily_limit
        FROM card_limit
        WHERE daily_limit > 0 AND used_amount * 10 >= daily_limit * 9
        ORDER BY used_amount * 10000 / daily_limit DESC;
    EXEC SQL OPEN exa;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH exa INTO :h_card, :h_bps;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d]\n", sqlca.sqlcode); EXEC SQL CLOSE exa; tpabort(0); return 1; }
        userlog("au_exhaust_alert 소진임박 card=%s %ldbps", h_card, h_bps);
        alerts++;
    }
    EXEC SQL CLOSE exa;

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

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