/* @tier hard @module vl @transform validation-online */
/*
 * vl_ol_0004.pgc - 중복거래 검출 서비스 (VL_OL_0004)
 *
 * 동일 카드번호 + 동일 금액 + 동일 거래일자로 접수된 원장(vl_ledger) 건수를
 * 집계하여 2건 이상이면 중복거래로 판정한다. 중복 판정 시 표준 에러코드
 * (VL04xx) 를 응답에 실어 반환하고, 정상(1건 이하)이면 정합으로 처리한다.
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

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

EXEC SQL INCLUDE sqlca;

TX_SERVICE(VL_OL_0004, ctx)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_card[20];
    char h_txndate[9];
    long h_amount;
    long h_dupcnt;
    EXEC SQL END DECLARE SECTION;

    char card[20], txndate[16];
    long amount = 0;

    tx_log(TX_LOG_INFO, "[VL_OL_0004] 중복거래 검출 서비스 진입");

    /* 1) 입력 검증: 카드번호 + 거래일자 + 금액 */
    if (tx_buf_get(ctx->in, "CARDNO", card, sizeof(card)) != TX_OK ||
        tx_buf_get(ctx->in, "TXNDATE", txndate, sizeof(txndate)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[VL_OL_0004] 필수 필드 누락(CARDNO/TXNDATE)");
        tx_buf_sets(ctx->out, "ERRCODE", "VL0400");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }
    tx_buf_getlong(ctx->in, "AMOUNT", &amount);

    if (strlen(card) < 12 || !date_is_valid(txndate) || !amount_is_valid(amount)) {
        tx_log(TX_LOG_WARN, "[VL_OL_0004] 입력값 형식 오류 card_len=%d date=%s amt=%ld",
               (int)strlen(card), txndate, amount);
        tx_buf_sets(ctx->out, "ERRCODE", "VL0401");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    /* 2) 동일 키 조합 건수 집계 */
    strncpy(h_card, card, sizeof(h_card) - 1);       h_card[sizeof(h_card) - 1] = '\0';
    strncpy(h_txndate, txndate, sizeof(h_txndate) - 1);
    h_txndate[sizeof(h_txndate) - 1] = '\0';
    h_amount = amount;
    h_dupcnt = 0;

    EXEC SQL
        SELECT COUNT(*)
          INTO :h_dupcnt
          FROM vl_ledger
         WHERE card_no  = :h_card
           AND amount   = :h_amount
           AND txn_date = :h_txndate;

    if (sqlca.sqlcode != TX_SQL_OK && sqlca.sqlcode != TX_SQL_NOTFOUND) {
        TX_DBIO_LOG_ERR("SELECT COUNT vl_ledger");
        tx_buf_sets(ctx->out, "ERRCODE", "VL0409");
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }

    /* 3) 중복 판정 */
    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "CARDNO", card);
    tx_buf_sets(ctx->out, "TXNDATE", txndate);
    tx_buf_setlong(ctx->out, "AMOUNT", amount);
    tx_buf_setlong(ctx->out, "DUPCNT", h_dupcnt);

    if (h_dupcnt >= 2) {
        tx_log(TX_LOG_WARN, "[VL_OL_0004] 중복거래 검출 card=%s cnt=%ld",
               card, h_dupcnt);
        tx_buf_sets(ctx->out, "RESULT", "DUPLICATE");
        tx_buf_sets(ctx->out, "ERRCODE", "VL0403");
        tx_return(ctx, TX_OK, ctx->out);
        return;
    }

    tx_buf_sets(ctx->out, "RESULT", "UNIQUE");
    tx_buf_sets(ctx->out, "ERRCODE", RESP_OK);
    tx_log(TX_LOG_INFO, "[VL_OL_0004] 중복 없음 card=%s cnt=%ld", card, h_dupcnt);
    tx_return(ctx, TX_OK, ctx->out);
}
