/*
 * au_fraud_scan_batch.pgc - au 부정거래 스캔 배치 (GROUP BY HAVING + XA).
 *
 * Groups the day's authorizations by card and, for cards whose승인건수/합계 that
 * exceed velocity thresholds (HAVING), inserts a fraud_log row via the dbio
 * layer - all under ONE global XA transaction. Usage: au_fraud_scan_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "au_dbio.h"

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];
    char h_card[24];
    long h_cnt, h_sum, h_score;
    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 fsc CURSOR FOR
        SELECT card_no, count(*), coalesce(sum(amount),0)
        FROM au_authorization
        WHERE biz_date = :h_bizdate
        GROUP BY card_no
        HAVING count(*) > 5 OR coalesce(sum(amount),0) > 5000000
        ORDER BY card_no;
    EXEC SQL OPEN fsc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH fsc INTO :h_card, :h_cnt, :h_sum;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE fsc; tpabort(0); return 1; }
        h_score = h_cnt * 10 + (h_sum > 5000000 ? 40 : 0);
        if (audb_insert_fraud(0, h_card, h_score, "VELOCITY_BATCH", bizdate) < 0) {
            EXEC SQL CLOSE fsc; tpabort(0); return 1;
        }
        rows++;
    }
    EXEC SQL CLOSE fsc;

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

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