/* @tier hard @module au @transform authorization-online */
/*
 * au_ol_0011.pgc - 이상거래 탐지(카드 단시간 다건) (AU_OL_0011)  [tier=hard]
 *
 * TxCore TX_SERVICE 엔트리. 요청 TXBUF 를 검증하고 임베디드 SQL / 표준
 * DBIO / tx_call 로 처리한 뒤 응답 TXBUF 를 구성한다.
 */
#include <stdio.h>
#include <string.h>

#include "txcore.h"
#include "txcore_dbio.h"
#include "acq_util.h"
#include "au_core.h"

EXEC SQL INCLUDE sqlca;

TX_SERVICE(AU_OL_0011, ctx)
{
    char key[16];
    if (tx_buf_get(ctx->in, "KEY", key, sizeof(key)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[AU_OL_0011] KEY 누락");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }
    EXEC SQL BEGIN DECLARE SECTION;
    char h_card[20], h_bdate[9];
    int  h_cnt;
    long h_sum;
    EXEC SQL END DECLARE SECTION;

    char card[20], bdate[16];
    int  fraud = 0;

    tx_log(TX_LOG_INFO, "[AU_OL_0011] 이상거래 탐지 진입");
    if (tx_buf_get(ctx->in, "CARDNO", card, sizeof(card)) != TX_OK) {
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }
    if (tx_buf_get(ctx->in, "BIZDATE", bdate, sizeof(bdate)) != TX_OK)
        date_today(bdate);

    strncpy(h_card, card, 19); h_card[19] = '\0';
    strncpy(h_bdate, bdate, 8); h_bdate[8] = '\0';

    EXEC SQL SELECT count(*), coalesce(sum(amount), 0)
        INTO :h_cnt, :h_sum
        FROM au_ledger
        WHERE card_no = :h_card AND biz_date = :h_bdate;
    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("au_ol_0011 탐지");
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }

    if (h_cnt >= 10 || h_sum >= 30000000L)
        fraud = 1;

    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "CARDNO", card);
    tx_buf_setlong(ctx->out, "TXNCNT", h_cnt);
    tx_buf_setlong(ctx->out, "TXNSUM", h_sum);
    tx_buf_sets(ctx->out, "FRAUD", fraud ? "Y" : "N");
    tx_buf_sets(ctx->out, "RESPCODE", fraud ? RESP_INVALID : RESP_OK);
    tx_log(TX_LOG_INFO, "[AU_OL_0011] 탐지결과 card=%s cnt=%d sum=%ld fraud=%d",
           card, h_cnt, h_sum, fraud);
    tx_return(ctx, fraud ? TX_FAIL : TX_OK, ctx->out);
}
