/*
 * vl_anomaly_batch.pgc - 이상거래(고액/0원) 탐지 배치 (커서 + XA).
 *
 * Cursors over a biz_date's 매입 whose amount exceeds the AMT_MAX rule threshold
 * or is non-positive, and that is not already flagged; each is written to
 * vl_suspect (via dbio) under ONE global XA transaction.
 * Usage: vl_anomaly_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "vl_dbio.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    long flagged = 0;
    char sev[8] = "ERROR";

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_pid, h_amt, thr = 50000000;
    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; }

    /* 규칙 임계 로드 (dbio) - 없으면 기본값 유지 */
    if (vldb_get_rule("AMT_MAX", &thr, sev) < 0) { thr = 50000000; strcpy(sev, "ERROR"); }

    EXEC SQL DECLARE vac CURSOR FOR
        SELECT p.purchase_id, p.amount FROM purchase p
        WHERE p.biz_date = :h_bizdate
          AND (p.amount > :thr OR p.amount <= 0)
          AND NOT EXISTS (SELECT 1 FROM vl_suspect s
                          WHERE s.purchase_id = p.purchase_id AND s.rule_code = 'AMT_MAX')
        ORDER BY p.purchase_id;
    EXEC SQL OPEN vac;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH vac INTO :h_pid, :h_amt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE vac; tpabort(0); return 1; }
        if (vldb_insert_suspect(h_pid, "AMT_MAX", sev,
                                (h_amt <= 0) ? "0원/음수 금액" : "고액 이상거래", bizdate) < 0) {
            EXEC SQL CLOSE vac; tpabort(0); return 1;
        }
        flagged++;
    }
    EXEC SQL CLOSE vac;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> vl_anomaly_batch COMMIT: bizdate=%s 임계=%ld 적출=%ld\n", bizdate, thr, flagged);

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