/* 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_0013.pgc"
/* @tier medium @module mg @transform msg-gateway-online */
/*
 * mg_ol_0013.pgc - 전문게이트웨이 채널별 어댑터 서비스 (MG_OL_0013)  [tier=medium]
 *
 * 채널마다 상이한 수신 헤더 포맷을 표준공통헤더(STDHDR)로 정규화한다.
 * 채널코드(CHAN)별 규칙은 in-code switch 로 분기하며, 각 채널이 자신의
 * 헤더에 배치한 전문종별/전문길이/일시 오프셋을 표준 배열로 재배치한다.
 * 표준헤더 = 전문종별(4) + 채널(3) + 전문길이(5) + 일시(14) = 26바이트.
 */
#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 17 "app/online/mg_ol_0013.pgc"


/* 채널 어댑터 정규화 규칙 */
#define STD_HDR_LEN 26

TX_SERVICE(MG_OL_0013, ctx)
{
    char raw[256];
    char chan[8];
    char stdhdr[STD_HDR_LEN + 1];
    char mtype[FLD_MSG_TYPE_LEN + 1];
    char yyyymmdd[9];
    char hhmmss[7];
    int  rawlen;
    int  bodyoff;
    int  chan3;

    tx_log(TX_LOG_INFO, "[MG_OL_0013] 채널별 어댑터 서비스 진입");

    rawlen = tx_buf_get(ctx->in, "RAWMSG", raw, sizeof(raw));
    if (rawlen <= 0 ||
        tx_buf_get(ctx->in, "CHAN", chan, sizeof(chan)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[MG_OL_0013] 필수 필드 누락(RAWMSG/CHAN)");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }
    rawlen = (int)strlen(raw);

    memset(mtype, 0, sizeof(mtype));
    memset(yyyymmdd, 0, sizeof(yyyymmdd));
    memset(hhmmss, 0, sizeof(hhmmss));

    /* 채널별 헤더 규칙 분기: 각 채널이 필드를 서로 다른 오프셋에 둔다 */
    if (strcmp(chan, "VAN") == 0) {
        /* VAN(부가통신): [종별4][일시14][본문...] */
        if (rawlen < 18) { bodyoff = -1; }
        else {
            memcpy(mtype, raw + 0, 4);
            memcpy(yyyymmdd, raw + 4, 8);
            memcpy(hhmmss, raw + 12, 6);
            bodyoff = 18;
        }
        chan3 = 0;
    } else if (strcmp(chan, "PGW") == 0) {
        /* PGW(전자지불): [일시14][종별4][본문...] - 순서 반전 */
        if (rawlen < 18) { bodyoff = -1; }
        else {
            memcpy(yyyymmdd, raw + 0, 8);
            memcpy(hhmmss, raw + 8, 6);
            memcpy(mtype, raw + 14, 4);
            bodyoff = 18;
        }
        chan3 = 1;
    } else if (strcmp(chan, "MPI") == 0) {
        /* MPI(모바일): [종별4][채널프리픽스2][일시14][본문...] */
        if (rawlen < 20) { bodyoff = -1; }
        else {
            memcpy(mtype, raw + 0, 4);
            memcpy(yyyymmdd, raw + 6, 8);
            memcpy(hhmmss, raw + 14, 6);
            bodyoff = 20;
        }
        chan3 = 2;
    } else {
        tx_log(TX_LOG_WARN, "[MG_OL_0013] 미지원 채널코드 chan=%s", chan);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_INVALID);
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    if (bodyoff < 0) {
        tx_log(TX_LOG_WARN, "[MG_OL_0013] 헤더 길이부족 chan=%s len=%d", chan, rawlen);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_INVALID);
        tx_return(ctx, TX_FAIL, ctx->out);
        return;
    }

    /* 종별 검증: 정규화 대상은 수신/응답/정산 전문만 허용 */
    if (strncmp(mtype, MSG_TYPE_RECV, 4) != 0 &&
        strncmp(mtype, MSG_TYPE_RESP, 4) != 0 &&
        strncmp(mtype, MSG_TYPE_RECON, 4) != 0) {
        tx_log(TX_LOG_WARN, "[MG_OL_0013] 전문종별 오류 chan=%s type=%.4s", chan, mtype);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_INVALID);
        tx_return(ctx, TX_FAIL, ctx->out);
        return;
    }

    /* 표준공통헤더 재배치: 종별(4)+채널(3)+본문길이(5)+일자(8)+시각(6) */
    memset(stdhdr, ' ', STD_HDR_LEN);
    stdhdr[STD_HDR_LEN] = '\0';
    memcpy(stdhdr + 0, mtype, 4);
    memcpy(stdhdr + 4, chan, (strlen(chan) < 3) ? strlen(chan) : 3);
    snprintf(stdhdr + 7, 6, "%05d", rawlen - bodyoff);
    memcpy(stdhdr + 12, yyyymmdd, 8);
    memcpy(stdhdr + 20, hhmmss, 6);

    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "RESPCODE", RESP_OK);
    tx_buf_sets(ctx->out, "STDHDR", stdhdr);
    tx_buf_sets(ctx->out, "MSGTYPE", mtype);
    tx_buf_sets(ctx->out, "TXNDATE", yyyymmdd);
    tx_buf_sets(ctx->out, "TXNTIME", hhmmss);
    tx_buf_sets(ctx->out, "BODY", raw + bodyoff);
    tx_buf_setlong(ctx->out, "CHANIDX", (long)chan3);
    tx_buf_setlong(ctx->out, "BODYLEN", (long)(rawlen - bodyoff));
    tx_log(TX_LOG_INFO, "[MG_OL_0013] 정규화 완료 chan=%s type=%.4s bodylen=%d",
           chan, mtype, rawlen - bodyoff);
    tx_return(ctx, TX_OK, ctx->out);
}
