/*
 * FRAUD_DETECT.pgc - au 모듈 서비스 FRAUD_DETECT (one service = one file).
 * 부정거래 스코어링 + 위험시 fraud_log 기록.
 * Moved verbatim from the former inline au_svr.pgc; runs on the caller's XA
 * branch (no EXEC SQL CONNECT). Advertised by au_svr at tpsvrinit.
 */
#include "FRAUD_DETECT.h"

void FRAUD_DETECT(TPSVCINFO *p)
{
    UBFH *b = (UBFH *)p->data;
    char card[24], bizdate[16], reason[128];
    long auth_id, amount, score = 0, fraud_id;
    EXEC SQL BEGIN DECLARE SECTION;
    long h_cnt;
    char h_card[24];
    EXEC SQL END DECLARE SECTION;

    auth_id = getl(b, T_ID1);
    amount = getl(b, T_AMOUNT);
    gets_(b, T_KEY1, card, sizeof(card));
    gets_(b, T_BIZDATE, bizdate, sizeof(bizdate));
    strncpy(h_card, card, sizeof(h_card)-1); h_card[sizeof(h_card)-1] = 0;

    /* 룰: 고액 + 당일 승인건수 과다 = 스코어 상승 */
    if (amount > 1000000) score += 50;
    EXEC SQL SELECT count(*) INTO :h_cnt FROM au_authorization WHERE card_no = :h_card;
    if (sqlca.sqlcode < 0) FAIL(b);
    if (h_cnt > 5) score += 40;
    score += (h_cnt * 2);

    strcpy(reason, score >= 50 ? "HIGH_RISK" : "OK");
    setl(b, T_ARG1, score);
    if (score >= 50) {
        fraud_id = audb_insert_fraud(auth_id, card, score, reason, bizdate);
        if (fraud_id < 0) FAIL(b);
        setl(b, T_ID2, fraud_id);
        setl(b, T_RC, 1);
    } else {
        setl(b, T_RC, 0);
    }
    OK(b);
}
