/* @tier medium @module mg @transform msg-gateway-online */
/*
 * mg_ol_0025.pgc - 전문게이트웨이 전문 중복 검출 서비스 (MG_OL_0025)  [tier=medium]
 *
 * STAN(전송추적번호)+금액+가맹점 조합으로 중복검출 해시를 계산하고,
 * 최근 처리원장(mg_ledger)에서 동일 조합을 조회하여 중복 여부를 판정한다.
 * 중복이면 기존 처리키를 반환하고, 신규면 통과시킨다.
 * (ATMI void SVC(TPSVCINFO*) 대응)
 */
#include <stdio.h>
#include <string.h>

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

EXEC SQL INCLUDE sqlca;

/* STAN+금액+가맹점 조합의 djb2 변형 해시 (중복탐지 지문) */
static long dup_fingerprint(const char *stan, long amount, const char *merch)
{
    unsigned long h = 5381UL;
    const char *p;
    char amt[24];
    int i;

    for (p = stan; *p; p++)
        h = ((h << 5) + h) ^ (unsigned char)*p;
    for (p = merch; *p; p++)
        h = ((h << 5) + h) ^ (unsigned char)*p;
    snprintf(amt, sizeof(amt), "%ld", amount);
    for (i = 0; amt[i]; i++)
        h = ((h << 5) + h) ^ (unsigned char)amt[i];

    return (long)(h & 0x7fffffffUL);
}

TX_SERVICE(MG_OL_0025, ctx)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_stan[13];
    char h_merch[16];
    long h_amount;
    char h_dup_key[16];
    EXEC SQL END DECLARE SECTION;

    char stan[13], merch[16];
    long amount = 0;
    long fp;

    tx_log(TX_LOG_INFO, "[MG_OL_0025] 전문 중복 검출 서비스 진입");

    /* 1) 검출키 구성요소 수신 */
    if (tx_buf_get(ctx->in, "STAN", stan, sizeof(stan)) != TX_OK ||
        tx_buf_get(ctx->in, "MERCHID", merch, sizeof(merch)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[MG_OL_0025] 필수 필드(STAN/MERCHID) 누락");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }
    tx_buf_getlong(ctx->in, "AMOUNT", &amount);

    /* 2) 중복검출 지문 계산 */
    fp = dup_fingerprint(stan, amount, merch);

    strncpy(h_stan, stan, sizeof(h_stan) - 1);
    h_stan[sizeof(h_stan) - 1] = '\0';
    strncpy(h_merch, merch, sizeof(h_merch) - 1);
    h_merch[sizeof(h_merch) - 1] = '\0';
    h_amount = amount;
    memset(h_dup_key, 0, sizeof(h_dup_key));

    /* 3) 최근 처리원장에서 동일 조합 조회 (최근 1건) */
    EXEC SQL
        SELECT key INTO :h_dup_key
          FROM mg_ledger
         WHERE stan = :h_stan
           AND merch_id = :h_merch
           AND amount = :h_amount
         ORDER BY req_ts DESC
         LIMIT 1;

    if (sqlca.sqlcode == TX_SQL_NOTFOUND) {
        tx_log(TX_LOG_INFO, "[MG_OL_0025] 중복없음 stan=%s fp=%ld", stan, fp);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESP", RESP_OK);
        tx_buf_sets(ctx->out, "DUP", "N");
        tx_buf_setlong(ctx->out, "FINGERPRINT", fp);
        tx_return(ctx, TX_OK, ctx->out);
        return;
    }
    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("SELECT mg_ledger(중복조회)");
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESP", RESP_SYSERR);
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }

    /* 4) 중복 판정 */
    tx_log(TX_LOG_WARN, "[MG_OL_0025] 중복검출 stan=%s dupkey=%s fp=%ld",
           stan, h_dup_key, fp);
    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "RESP", RESP_INVALID);
    tx_buf_sets(ctx->out, "DUP", "Y");
    tx_buf_sets(ctx->out, "DUPKEY", h_dup_key);
    tx_buf_setlong(ctx->out, "FINGERPRINT", fp);
    tx_return(ctx, TX_FAIL, ctx->out);
}
