/* Processed by ecpg (15.18 (Debian 15.18-0+deb12u1)) */
/* These include files are added by the preprocessor */
#include <ecpglib.h>
#include <ecpgerrno.h>
#include <sqlca.h>
/* End of automatic include section */

#line 1 "app/online/mg_ol_0025.pgc"
/* @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"


#line 1 "/usr/include/postgresql/sqlca.h"
#ifndef POSTGRES_SQLCA_H
#define POSTGRES_SQLCA_H

#ifndef PGDLLIMPORT
#if  defined(WIN32) || defined(__CYGWIN__)
#define PGDLLIMPORT __declspec (dllimport)
#else
#define PGDLLIMPORT
#endif							/* __CYGWIN__ */
#endif							/* PGDLLIMPORT */

#define SQLERRMC_LEN	150

#ifdef __cplusplus
extern "C"
{
#endif

struct sqlca_t
{
	char		sqlcaid[8];
	long		sqlabc;
	long		sqlcode;
	struct
	{
		int			sqlerrml;
		char		sqlerrmc[SQLERRMC_LEN];
	}			sqlerrm;
	char		sqlerrp[8];
	long		sqlerrd[6];
	/* Element 0: empty						*/
	/* 1: OID of processed tuple if applicable			*/
	/* 2: number of rows processed				*/
	/* after an INSERT, UPDATE or				*/
	/* DELETE statement					*/
	/* 3: empty						*/
	/* 4: empty						*/
	/* 5: empty						*/
	char		sqlwarn[8];
	/* Element 0: set to 'W' if at least one other is 'W'	*/
	/* 1: if 'W' at least one character string		*/
	/* value was truncated when it was			*/
	/* stored into a host variable.             */

	/*
	 * 2: if 'W' a (hopefully) non-fatal notice occurred
	 */	/* 3: empty */
	/* 4: empty						*/
	/* 5: empty						*/
	/* 6: empty						*/
	/* 7: empty						*/

	char		sqlstate[5];
};

struct sqlca_t *ECPGget_sqlca(void);

#ifndef POSTGRES_ECPG_INTERNAL
#define sqlca (*ECPGget_sqlca())
#endif

#ifdef __cplusplus
}
#endif

#endif

#line 18 "app/online/mg_ol_0025.pgc"


/* 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 */
     
     
     
     
    
#line 42 "app/online/mg_ol_0025.pgc"
 char h_stan [ 13 ] ;
 
#line 43 "app/online/mg_ol_0025.pgc"
 char h_merch [ 16 ] ;
 
#line 44 "app/online/mg_ol_0025.pgc"
 long h_amount ;
 
#line 45 "app/online/mg_ol_0025.pgc"
 char h_dup_key [ 16 ] ;
/* exec sql end declare section */
#line 46 "app/online/mg_ol_0025.pgc"


    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건) */
    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select key from mg_ledger where stan = $1  and merch_id = $2  and amount = $3  order by req_ts desc limit 1", 
	ECPGt_char,(h_stan),(long)13,(long)1,(13)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_char,(h_merch),(long)16,(long)1,(16)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_amount),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, 
	ECPGt_char,(h_dup_key),(long)16,(long)1,(16)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT);}
#line 81 "app/online/mg_ol_0025.pgc"


    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);
}
