/*
 * au_noauth_detect_batch.pgc - au 무승인 매입 검출 배치 (NOT EXISTS 안티조인, XA).
 *
 * 영업일의 매입원장(purchase) 전수와, 같은 가맹점/영업일/금액의 유효 승인이
 * 승인원장에 없는 매입(무승인 매입 의심)을 안티조인 두 번의 집계로 뽑아
 * 의심비중 기반 심각도(CLEAN/MINOR/MAJOR)를 판정한다.
 * Usage: au_noauth_detect_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "au_noauth_detect_batch.h"

int aub_noauth_severity(long suspects, long purchases)
{
    if (suspects == 0 || purchases == 0) return 0;
    if (suspects * 100 >= purchases * 5) return 2;   /* 5% 이상이면 MAJOR */
    return 1;
}

int main(int argc, char **argv)
{
    static const char *sev_name[] = { "CLEAN", "MINOR", "MAJOR" };
    au_noauth_detect_ctx_t ctx;
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    int sev;

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_all = 0, h_bad = 0, h_badamt = 0;
    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;

    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 SELECT count(*) INTO :h_all FROM purchase
        WHERE biz_date = :h_bizdate AND status NOT IN ('C','V');
    if (sqlca.sqlcode < 0) { fprintf(stderr, "COUNT FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    EXEC SQL SELECT count(*), coalesce(sum(p.amount),0) INTO :h_bad, :h_badamt
        FROM purchase p
        WHERE p.biz_date = :h_bizdate AND p.status NOT IN ('C','V')
          AND NOT EXISTS (SELECT 1 FROM au_authorization a
                           WHERE a.merchant_id = p.merchant_id
                             AND a.biz_date = p.biz_date
                             AND a.amount = p.amount
                             AND a.status IN ('A','M','S'));
    if (sqlca.sqlcode < 0) { fprintf(stderr, "DETECT FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    ctx.purchases = h_all;
    ctx.suspects = h_bad;
    ctx.suspect_gross = h_badamt;
    sev = aub_noauth_severity(ctx.suspects, ctx.purchases);

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> au_noauth_detect_batch COMMIT: bizdate=%s 매입=%ld 무승인의심=%ld건 %ld원 심각도=%s\n",
           ctx.biz_date, ctx.purchases, ctx.suspects, ctx.suspect_gross, sev_name[sev]);

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