/* 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_0012.pgc"
/* @tier medium @module mg @transform msg-gateway-online */
/*
 * mg_ol_0012.pgc - 전문 검증 서비스 (MG_OL_0012)  [tier=medium]
 *
 * 고정길이 수신전문(RAWMSG)에 대해 (1)필수필드 존재, (2)전문종별 유효성,
 * (3)금액/일자 숫자필드의 mod-10 체크숫자를 순차 검증한다. 각 단계 결과를
 * 비트플래그로 누적하여 최종 검증 결과코드를 응답한다.
 */
#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_0012.pgc"


/* 검증 단계 플래그 */
#define MG12_F_FIELD  0x01   /* 필수필드 OK */
#define MG12_F_TYPE   0x02   /* 전문종별 OK */
#define MG12_F_CHECK  0x04   /* 체크숫자 OK */
#define MG12_F_ALL    (MG12_F_FIELD | MG12_F_TYPE | MG12_F_CHECK)

TX_SERVICE(MG_OL_0012, ctx)
{
    char       raw[MSG_ACQ_LEN + 8];
    char       chkbuf[8];
    acq_msg_t  msg;
    int        flags;
    int        i, sum, calc;
    long       parsed_chk;

    tx_log(TX_LOG_INFO, "[MG_OL_0012] 전문 검증 서비스 진입");

    /* 1) 원시전문 수신 및 언팩 */
    if (tx_buf_get(ctx->in, "RAWMSG", raw, sizeof(raw)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[MG_OL_0012] 원시전문(RAWMSG) 누락");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }
    memset(&msg, 0, sizeof(msg));
    if (msg_unpack(&msg, raw, MSG_ACQ_LEN) != 0) {
        tx_log(TX_LOG_ERROR, "[MG_OL_0012] 전문 언팩 실패");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    flags = 0;

    /* 2) 필수필드 검증 */
    if (msg_validate(&msg) == 0)
        flags |= MG12_F_FIELD;
    else
        tx_log(TX_LOG_WARN, "[MG_OL_0012] 필수필드 검증 실패");

    /* 3) 전문종별 유효성 */
    if (strncmp(msg.msg_type, MSG_TYPE_RECV, FLD_MSG_TYPE_LEN) == 0 ||
        strncmp(msg.msg_type, MSG_TYPE_RESP, FLD_MSG_TYPE_LEN) == 0 ||
        strncmp(msg.msg_type, MSG_TYPE_RECON, FLD_MSG_TYPE_LEN) == 0)
        flags |= MG12_F_TYPE;
    else
        tx_log(TX_LOG_WARN, "[MG_OL_0012] 전문종별 무효 type=%.4s", msg.msg_type);

    /* 4) 체크숫자: 금액 12자리 숫자합 mod 10 */
    sum = 0;
    for (i = 0; i < FLD_AMOUNT_LEN; i++) {
        char c = msg.amount[i];
        if (c >= '0' && c <= '9')
            sum += (c - '0');
        else if (c != ' ') {
            sum = -1;
            break;
        }
    }
    calc = (sum >= 0) ? (sum % 10) : -1;

    /* 입력에 기대 체크숫자(CHKDIGIT)가 오면 대조, 없으면 계산값을 신뢰 */
    if (calc >= 0) {
        if (tx_buf_get(ctx->in, "CHKDIGIT", chkbuf, sizeof(chkbuf)) == TX_OK &&
            chkbuf[0] != '\0') {
            parsed_chk = amount_parse(chkbuf, (int)strlen(chkbuf));
            if (parsed_chk == (long)calc)
                flags |= MG12_F_CHECK;
            else
                tx_log(TX_LOG_WARN, "[MG_OL_0012] 체크숫자 불일치 calc=%d exp=%ld",
                       calc, parsed_chk);
        } else {
            flags |= MG12_F_CHECK;   /* 기대값 미제공 시 계산성공을 통과로 간주 */
        }
    } else {
        tx_log(TX_LOG_WARN, "[MG_OL_0012] 금액필드 비숫자 포함 -> 체크숫자 산출불가");
    }

    /* 5) 최종 판정 및 결과코드 응답 */
    tx_buf_reset(ctx->out);
    if (flags == MG12_F_ALL) {
        tx_buf_sets(ctx->out, "RESP", RESP_OK);
        tx_buf_setlong(ctx->out, "VALID", 1);
        tx_log(TX_LOG_INFO, "[MG_OL_0012] 전문 검증통과 type=%.4s chk=%d",
               msg.msg_type, calc);
    } else {
        tx_buf_sets(ctx->out, "RESP", RESP_INVALID);
        tx_buf_setlong(ctx->out, "VALID", 0);
        tx_log(TX_LOG_WARN, "[MG_OL_0012] 전문 검증실패 flags=0x%02x", flags);
    }
    tx_buf_setlong(ctx->out, "FLAGS", (long)flags);
    tx_buf_setlong(ctx->out, "CHKDIGIT", (long)calc);

    /* 6) 검증 결과(mg_validate_log)를 임베디드 SQL 로 적재 */
    {
        /* exec sql begin declare section */
         
         
         
         
        
#line 113 "app/online/mg_ol_0012.pgc"
 char h_v_type [ 8 ] ;
 
#line 114 "app/online/mg_ol_0012.pgc"
 long h_v_flags ;
 
#line 115 "app/online/mg_ol_0012.pgc"
 long h_v_chk ;
 
#line 116 "app/online/mg_ol_0012.pgc"
 long h_v_valid ;
/* exec sql end declare section */
#line 117 "app/online/mg_ol_0012.pgc"


        msg_field_copy(h_v_type, msg.msg_type, FLD_MSG_TYPE_LEN);
        h_v_flags = (long)flags;
        h_v_chk   = (long)calc;
        h_v_valid = (flags == MG12_F_ALL) ? 1 : 0;

        if (tx_begin() == TX_OK) {
            { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "insert into mg_validate_log ( msg_type , check_flags , check_digit , valid_yn ) values ( $1  , $2  , $3  , $4  )", 
	ECPGt_char,(h_v_type),(long)8,(long)1,(8)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_v_flags),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_v_chk),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_v_valid),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, ECPGt_EORT);}
#line 127 "app/online/mg_ol_0012.pgc"

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

    tx_return(ctx, (flags == MG12_F_ALL) ? TX_OK : TX_FAIL, ctx->out);
}
