/* 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_0001.pgc"
/* @tier easy @module mg @transform msg-gateway-online */
/*
 * mg_ol_0001.pgc - 전문게이트웨이 전문 수신 서비스 (MG_OL_0001)  [tier=easy]
 *
 * 채널로부터 수신한 고정길이 원시전문(0200)을 acq_msg_t 로 언팩/검증한
 * 뒤, 전문게이트웨이 원장(mg_ledger)에 접수상태('R')로 적재한다.
 * (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 17 "app/online/mg_ol_0001.pgc"


TX_SERVICE(MG_OL_0001, ctx)
{
    char       raw[256];
    int        rawlen;
    acq_msg_t  msg;
    mg_rec_t   rec;
    long       amount;
    int        rc;

    tx_log(TX_LOG_INFO, "[MG_OL_0001] 전문 수신 서비스 진입");

    /* 1) 원시전문 수신 (고정길이 프레임) */
    rawlen = tx_buf_get(ctx->in, "RAWMSG", raw, sizeof(raw));
    if (rawlen <= 0) {
        tx_log(TX_LOG_ERROR, "[MG_OL_0001] 원시전문(RAWMSG) 누락");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    /* 2) 고정길이 언팩 */
    memset(&msg, 0, sizeof(msg));
    if (msg_unpack(&msg, raw, (int)strlen(raw)) != 0) {
        tx_log(TX_LOG_ERROR, "[MG_OL_0001] 전문 언팩 실패 len=%d", (int)strlen(raw));
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    /* 3) 전문 검증 (전문종별/필수필드) */
    if (msg_validate(&msg) != 0 ||
        strncmp(msg.msg_type, MSG_TYPE_RECV, FLD_MSG_TYPE_LEN) != 0) {
        tx_log(TX_LOG_WARN, "[MG_OL_0001] 전문 검증 실패 type=%.4s", msg.msg_type);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESP", RESP_INVALID);
        tx_return(ctx, TX_FAIL, ctx->out);
        return;
    }

    /* 4) 구조체 -> 원장 레코드 매핑 */
    amount = amount_parse(msg.amount, FLD_AMOUNT_LEN);
    memset(&rec, 0, sizeof(rec));
    msg_field_copy(rec.key,      msg.approval_no, FLD_APPROVAL_LEN);
    msg_field_copy(rec.merch_id, msg.merch_id,    FLD_MERCH_ID_LEN);
    msg_field_copy(rec.card_no,  msg.card_no,     FLD_CARD_NO_LEN);
    msg_field_copy(rec.biz_date, msg.txn_date,    FLD_TXN_DATE_LEN);
    rec.amount = amount;
    rec.fee    = 0;
    strncpy(rec.status, MG_ST_RECV, sizeof(rec.status) - 1);

    /* 5) 원장 적재 */
    rc = mg_rec_insert(&rec);
    if (rc != TX_OK) {
        tx_log(TX_LOG_ERROR, "[MG_OL_0001] 원장 적재 실패 key=%s rc=%d(%s)",
               rec.key, rc, tx_strerror(rc));
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESP", RESP_SYSERR);
        tx_return(ctx, rc, ctx->out);
        return;
    }

    /* 5-b) 원시전문 수신 저널(mg_recv_log)에 임베디드 SQL 로 접수 이력 적재 */
    {
        /* exec sql begin declare section */
         
         
         
         
        
#line 81 "app/online/mg_ol_0001.pgc"
 char h_rv_key [ 16 ] ;
 
#line 82 "app/online/mg_ol_0001.pgc"
 char h_rv_merch [ 16 ] ;
 
#line 83 "app/online/mg_ol_0001.pgc"
 long h_rv_amount ;
 
#line 84 "app/online/mg_ol_0001.pgc"
 long h_rv_rawlen ;
/* exec sql end declare section */
#line 85 "app/online/mg_ol_0001.pgc"


        strncpy(h_rv_key, rec.key, sizeof(h_rv_key) - 1);
        h_rv_key[sizeof(h_rv_key) - 1] = '\0';
        strncpy(h_rv_merch, rec.merch_id, sizeof(h_rv_merch) - 1);
        h_rv_merch[sizeof(h_rv_merch) - 1] = '\0';
        h_rv_amount = rec.amount;
        h_rv_rawlen = (long)strlen(raw);

        if (tx_begin() == TX_OK) {
            { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "insert into mg_recv_log ( recv_key , merch_id , recv_amount , raw_len , recv_status ) values ( $1  , $2  , $3  , $4  , 'R' )", 
	ECPGt_char,(h_rv_key),(long)16,(long)1,(16)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_char,(h_rv_merch),(long)16,(long)1,(16)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_rv_amount),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_rv_rawlen),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, ECPGt_EORT);}
#line 97 "app/online/mg_ol_0001.pgc"

            if (sqlca.sqlcode != TX_SQL_OK) {
                TX_DBIO_LOG_ERR("INSERT mg_recv_log");
                tx_abort();
            } else {
                tx_commit();
            }
        }
    }

    /* 6) 수신확인 응답 구성 */
    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "RESP", RESP_OK);
    tx_buf_sets(ctx->out, "KEY", rec.key);
    tx_buf_setlong(ctx->out, "AMOUNT", rec.amount);
    tx_buf_sets(ctx->out, "STATUS", rec.status);
    tx_log(TX_LOG_INFO, "[MG_OL_0001] 전문 수신완료 key=%s amount=%ld", rec.key, rec.amount);
    tx_return(ctx, TX_OK, ctx->out);
}
