/*
 * au_pertx_audit_batch.pgc - au 건별 한도 초과 승인 감사 배치 (JOIN 커서 + XA).
 *
 * Joins the day's authorizations to card_limit and, for single transactions
 * exceeding 20% of the daily limit (per-tx cap), logs a fraud row via dbio,
 * all under ONE global XA transaction. Usage: au_pertx_audit_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "au_dbio.h"
EXEC SQL INCLUDE au_pertx_audit_batch;

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    long rows = 0;
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_card[24];
    long 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 pxa CURSOR FOR
        SELECT a.card_no, a.amount
        FROM au_authorization a JOIN card_limit l ON l.card_no = a.card_no
        WHERE a.biz_date = :h_bizdate AND a.amount > l.daily_limit / 5
        ORDER BY a.amount DESC;
    EXEC SQL OPEN pxa;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH pxa INTO :h_card, :h_amt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d]\n", sqlca.sqlcode); EXEC SQL CLOSE pxa; tpabort(0); return 1; }
        if (audb_insert_fraud(0, h_card, 500, "PERTX_OVER", bizdate) < 0) { EXEC SQL CLOSE pxa; tpabort(0); return 1; }
        rows++;
    }
    EXEC SQL CLOSE pxa;

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

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