/*
 * au_blacklist_hit_batch.pgc - au 블랙리스트 승인시도 검출 배치 (조인 커서 + 로그, XA).
 *
 * 영업일 승인원장을 블랙리스트와 조인해, 등재 카드로 들어온 승인 시도를
 * 카드 단위 커서로 적발한다. 카드마다 만점(999) 점수의 BLACKLIST_HIT
 * 부정거래 로그를 남기고 시도 건수를 함께 기록한다.
 * Usage: au_blacklist_hit_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "au_blacklist_hit_batch.h"

long aub_blacklist_hit_score(void)
{
    return 999;
}

int main(int argc, char **argv)
{
    au_blacklist_hit_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_tries, h_fid, h_score;
    EXEC SQL END DECLARE SECTION;

    memset(&ctx, 0, sizeof(ctx));
    strncpy(ctx.biz_date, bizdate, sizeof(ctx.biz_date)-1);
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    h_score = aub_blacklist_hit_score();

    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 cbhb CURSOR FOR
        SELECT a.card_no, count(*)
        FROM au_authorization a JOIN au_blacklist k ON k.card_no = a.card_no
        WHERE a.biz_date = :h_bizdate
        GROUP BY a.card_no ORDER BY count(*) DESC;
    EXEC SQL OPEN cbhb;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH cbhb INTO :h_card, :h_tries;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE cbhb; tpabort(0); return 1; }
        ctx.hit_cards++;
        ctx.hit_auths += h_tries;
        EXEC SQL SELECT nextval('au_fraud_seq') INTO :h_fid;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE cbhb; 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, 'BLACKLIST_HIT', :h_bizdate);
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE cbhb; tpabort(0); return 1; }
        ctx.logged++;
        printf("    블랙리스트 히트 card=%.6s** 시도=%ld건\n", h_card, h_tries);
    }
    EXEC SQL CLOSE cbhb;

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

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