/*
 * au_velocity_flag_batch.pgc - au velocity 위반 카드 일괄 적발 배치 (커서 + INSERT, XA).
 *
 * 영업일에 임계 건수를 초과 승인한 카드를 HAVING 커서로 골라, 카드별로
 * 부정거래 로그(au_fraud_log)에 RULE_VELOCITY_DAY 사유의 적발 행을 남긴다.
 * 모두 ONE global XA transaction 아래에서 수행된다.
 * Usage: au_velocity_flag_batch [YYYY-MM-DD] [임계건수]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "au_velocity_flag_batch.h"

long aub_velocity_score(long cnt, long threshold)
{
    long s = 650 + (cnt - threshold) * 15;
    return (s > 999) ? 999 : s;
}

int main(int argc, char **argv)
{
    au_velocity_flag_ctx_t ctx;
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_card[24];
    long h_thr, h_cnt, h_fid, h_score;
    EXEC SQL END DECLARE SECTION;

    memset(&ctx, 0, sizeof(ctx));
    strncpy(ctx.biz_date, bizdate, sizeof(ctx.biz_date)-1);
    ctx.threshold = (argc > 2) ? atol(argv[2]) : 10;
    if (ctx.threshold <= 0) ctx.threshold = 10;
    h_thr = ctx.threshold;
    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(120, 0) < 0) { fprintf(stderr, "tpbegin FAIL: %s\n", tpstrerror(tperrno)); return 1; }

    EXEC SQL DECLARE cvfb CURSOR FOR
        SELECT card_no, count(*) FROM au_authorization
        WHERE biz_date = :h_bizdate
        GROUP BY card_no HAVING count(*) > :h_thr
        ORDER BY count(*) DESC;
    EXEC SQL OPEN cvfb;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH cvfb INTO :h_card, :h_cnt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE cvfb; tpabort(0); return 1; }
        ctx.flagged_cards++;
        h_score = aub_velocity_score(h_cnt, h_thr);
        EXEC SQL SELECT nextval('au_fraud_seq') INTO :h_fid;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE cvfb; tpabort(0); return 1; }
        EXEC SQL INSERT INTO au_fraud_log (fraud_id, auth_id, card_no, score, reason, biz_date)
            VALUES (:h_fid, 0, :h_card, :h_score, 'RULE_VELOCITY_DAY', :h_bizdate);
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE cvfb; tpabort(0); return 1; }
        ctx.logged++;
    }
    EXEC SQL CLOSE cvfb;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> au_velocity_flag_batch COMMIT: bizdate=%s 임계=%ld건 적발카드=%ld 기록=%ld\n",
           ctx.biz_date, ctx.threshold, ctx.flagged_cards, ctx.logged);

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