/* 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_0006.pgc"
/* @tier medium @module mg @transform msg-gateway-online */
/*
 * mg_ol_0006.pgc - 전문 포맷 변환 서비스 (MG_OL_0006)  [tier=medium]
 *
 * 수신전문(0200)을 정산전문(0500)으로 변환한다. 원전문을 언팩하여 필드를
 * 재배치/보정(전문종별 교체, 거래코드 SETTLE 치환, 할부→일시불 정규화,
 * 응답코드 초기화)한 뒤 다시 팩하여 정산 RAWMSG 를 반환한다.
 */
#include <stdio.h>
#include <string.h>

#include "txcore.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 16 "app/online/mg_ol_0006.pgc"


TX_SERVICE(MG_OL_0006, ctx)
{
    char       raw[MSG_ACQ_LEN + 8];
    char       out[MSG_ACQ_LEN + 8];
    int        rawlen;
    acq_msg_t  src;
    acq_msg_t  dst;

    tx_log(TX_LOG_INFO, "[MG_OL_0006] 전문 포맷 변환(0200->0500) 서비스 진입");

    /* 1) 원시 수신전문 수신 */
    rawlen = tx_buf_get(ctx->in, "RAWMSG", raw, sizeof(raw));
    if (rawlen != TX_OK) {
        tx_log(TX_LOG_ERROR, "[MG_OL_0006] 원시전문(RAWMSG) 누락 rc=%d", rawlen);
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    /* 2) 언팩 및 원전문 종별 확인 */
    memset(&src, 0, sizeof(src));
    if (msg_unpack(&src, raw, MSG_ACQ_LEN) != 0) {
        tx_log(TX_LOG_ERROR, "[MG_OL_0006] 전문 언팩 실패");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }
    if (strncmp(src.msg_type, MSG_TYPE_RECV, FLD_MSG_TYPE_LEN) != 0) {
        tx_log(TX_LOG_WARN, "[MG_OL_0006] 변환 대상 아님 type=%.4s", src.msg_type);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESP", RESP_INVALID);
        tx_return(ctx, TX_FAIL, ctx->out);
        return;
    }

    /* 3) 정산전문(0500)으로 필드 재배치/보정 */
    memset(&dst, 0, sizeof(dst));
    /* 전문종별 교체 */
    msg_field_set(dst.msg_type, MSG_TYPE_RECON, FLD_MSG_TYPE_LEN);
    /* 거래코드는 SETTLE 로 치환 */
    msg_field_set(dst.trans_code, "SETTLE", FLD_TRANS_CODE_LEN);
    /* 식별/금액/일자 필드는 원전문 그대로 이관 */
    memcpy(dst.merch_id,    src.merch_id,    FLD_MERCH_ID_LEN);
    memcpy(dst.card_no,     src.card_no,     FLD_CARD_NO_LEN);
    memcpy(dst.approval_no, src.approval_no, FLD_APPROVAL_LEN);
    memcpy(dst.amount,      src.amount,      FLD_AMOUNT_LEN);
    memcpy(dst.txn_date,    src.txn_date,    FLD_TXN_DATE_LEN);
    memcpy(dst.txn_time,    src.txn_time,    FLD_TXN_TIME_LEN);

    /* 할부개월 정규화: 정산전문은 일시불('00')로 집계 */
    msg_field_set(dst.inst_month, "00", FLD_INST_LEN);
    /* 응답코드는 정산단계에서 미결('0000') 초기화 */
    msg_field_set(dst.resp_code, RESP_OK, FLD_RESP_LEN);
    /* 필러는 공백 채움 */
    memset(dst.filler, ' ', sizeof(dst.filler));

    /* 4) 변환전문 팩 */
    if (msg_pack(&dst, out, MSG_ACQ_LEN) != 0) {
        tx_log(TX_LOG_ERROR, "[MG_OL_0006] 변환전문 팩 실패");
        tx_return(ctx, TX_FAIL, ctx->out);
        return;
    }

    /* 5) 정산 RAWMSG 반환 */
    tx_buf_reset(ctx->out);
    tx_buf_set(ctx->out, "RAWMSG", out, MSG_ACQ_LEN);
    tx_buf_setlong(ctx->out, "RAWLEN", (long)MSG_ACQ_LEN);
    tx_buf_sets(ctx->out, "SRCTYPE", MSG_TYPE_RECV);
    tx_buf_sets(ctx->out, "DSTTYPE", MSG_TYPE_RECON);
    tx_buf_sets(ctx->out, "RESP", RESP_OK);
    tx_log(TX_LOG_INFO, "[MG_OL_0006] 포맷 변환완료 0200->0500 len=%d", MSG_ACQ_LEN);
    tx_return(ctx, TX_OK, ctx->out);
}
