/* 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_0007.pgc"
/* @tier easy @module mg @transform msg-gateway-online */
/*
 * mg_ol_0007.pgc - 오류전문 생성 서비스 (MG_OL_0007)  [tier=easy]
 *
 * 원전문(RAWMSG)과 오류코드(ERRCODE)를 받아 응답전문(0210)의 오류회신을
 * 구성한다. 원전문 식별필드는 그대로 보존하고 전문종별을 0210 으로 바꾼 뒤
 * resp_code 에 오류코드를 세팅하여 msg_pack 후 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_0007.pgc"


TX_SERVICE(MG_OL_0007, ctx)
{
    char       raw[MSG_ACQ_LEN + 8];
    char       out[MSG_ACQ_LEN + 8];
    char       errcode[8];
    int        rawlen;
    acq_msg_t  msg;

    tx_log(TX_LOG_INFO, "[MG_OL_0007] 오류전문 생성 서비스 진입");

    /* 1) 원전문 + 오류코드 수신 */
    rawlen = tx_buf_get(ctx->in, "RAWMSG", raw, sizeof(raw));
    if (rawlen != TX_OK) {
        tx_log(TX_LOG_ERROR, "[MG_OL_0007] 원전문(RAWMSG) 누락 rc=%d", rawlen);
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }
    if (tx_buf_get(ctx->in, "ERRCODE", errcode, sizeof(errcode)) != TX_OK ||
        errcode[0] == '\0') {
        /* 오류코드 미지정 시 시스템오류로 간주 */
        strncpy(errcode, RESP_SYSERR, sizeof(errcode) - 1);
        errcode[sizeof(errcode) - 1] = '\0';
    }

    /* 2) 오류코드 4자리 정규화 (부족분 zero-fill, 초과분 절단) */
    if ((int)strlen(errcode) != FLD_RESP_LEN) {
        char norm[FLD_RESP_LEN + 1];
        msg_field_set_num(norm, errcode, FLD_RESP_LEN);
        norm[FLD_RESP_LEN] = '\0';
        strncpy(errcode, norm, sizeof(errcode) - 1);
        errcode[sizeof(errcode) - 1] = '\0';
    }

    /* 3) 원전문 언팩 (식별필드 보존 목적) */
    memset(&msg, 0, sizeof(msg));
    if (msg_unpack(&msg, raw, MSG_ACQ_LEN) != 0) {
        tx_log(TX_LOG_ERROR, "[MG_OL_0007] 원전문 언팩 실패");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    /* 4) 오류응답으로 변환: 종별 0210, 응답코드 세팅, 금액 영처리 */
    msg_field_set(msg.msg_type, MSG_TYPE_RESP, FLD_MSG_TYPE_LEN);
    memcpy(msg.resp_code, errcode, FLD_RESP_LEN);
    msg_field_set_num(msg.amount, "0", FLD_AMOUNT_LEN);
    msg_field_set(msg.filler, "ERR", sizeof(msg.filler));

    /* 5) 팩 후 오류 RAWMSG 반환 */
    if (msg_pack(&msg, out, MSG_ACQ_LEN) != 0) {
        tx_log(TX_LOG_ERROR, "[MG_OL_0007] 오류전문 팩 실패");
        tx_return(ctx, TX_FAIL, ctx->out);
        return;
    }

    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, "MSGTYPE", MSG_TYPE_RESP);
    tx_buf_set(ctx->out, "RESPCODE", errcode, FLD_RESP_LEN);
    tx_log(TX_LOG_INFO, "[MG_OL_0007] 오류전문 생성완료 respcode=%.4s", errcode);
    tx_return(ctx, TX_OK, ctx->out);
}
