/* 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/cm_ol_0004.pgc"
/* @tier medium @module cm @transform common-online */
/*
 * cm_ol_0004.pgc - 전문 공통헤더 처리 서비스 (CM_OL_0004)  [tier=medium]
 *
 * 요청의 공통헤더 원천 필드(전문길이/전문종별/채널/거래일시)를 파싱·
 * 검증한 뒤, 고정 자리수의 표준 공통헤더 문자열로 재구성하여 응답한다.
 * 채널코드는 채널 마스터(cm_channel)를 조회하여 채널명/사용여부를
 * 확인하며, 미등록·미사용 채널이면 반려한다.
 * (ATMI void SVC(TPSVCINFO*) 대응)
 */
#include <stdio.h>
#include <string.h>

#include "txcore.h"
#include "txcore_dbio.h"
#include "acq_util.h"
#include "cm_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 19 "app/online/cm_ol_0004.pgc"


/* 전문종별 코드 → 표준 2자리 구분자 매핑 */
static const char *header_kind_tag(const char *kind)
{
    if (strcmp(kind, MSG_TYPE_RECV) == 0)  return "RQ";   /* 매입요청 */
    if (strcmp(kind, MSG_TYPE_RESP) == 0)  return "RP";   /* 응답     */
    if (strcmp(kind, MSG_TYPE_RECON) == 0) return "RC";   /* 정산대사 */
    return "XX";                                          /* 미정의   */
}

TX_SERVICE(CM_OL_0004, ctx)
{
    /* exec sql begin declare section */
     
     
     
    
#line 33 "app/online/cm_ol_0004.pgc"
 char h_channel [ 4 ] ;
 
#line 34 "app/online/cm_ol_0004.pgc"
 char h_channel_nm [ 40 ] ;
 
#line 35 "app/online/cm_ol_0004.pgc"
 char h_use_yn [ 2 ] ;
/* exec sql end declare section */
#line 36 "app/online/cm_ol_0004.pgc"


    char msglen_f[8];
    char kind[8];
    char channel[4];
    char datetime[16];
    char std_header[64];
    const char *tag;
    long msglen = 0;
    int  i;

    tx_log(TX_LOG_INFO, "[CM_OL_0004] 전문 공통헤더 처리 서비스 진입");

    memset(msglen_f, 0, sizeof(msglen_f));
    memset(kind, 0, sizeof(kind));
    memset(channel, 0, sizeof(channel));
    memset(datetime, 0, sizeof(datetime));
    memset(std_header, 0, sizeof(std_header));

    if (tx_buf_get(ctx->in, "MSGLEN", msglen_f, sizeof(msglen_f)) != TX_OK ||
        tx_buf_get(ctx->in, "MSGTYPE", kind, sizeof(kind)) != TX_OK ||
        tx_buf_get(ctx->in, "CHANNEL", channel, sizeof(channel)) != TX_OK ||
        tx_buf_get(ctx->in, "DATETIME", datetime, sizeof(datetime)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[CM_OL_0004] 공통헤더 필수 필드 누락");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    /* 전문길이 숫자검증 */
    for (i = 0; msglen_f[i] != '\0'; i++) {
        if (msglen_f[i] < '0' || msglen_f[i] > '9') {
            tx_log(TX_LOG_WARN, "[CM_OL_0004] 전문길이 형식오류 msglen=%s", msglen_f);
            tx_return(ctx, TX_EINVAL, ctx->out);
            return;
        }
    }
    msglen = amount_parse(msglen_f, (int)strlen(msglen_f));
    if (msglen <= 0 || msglen > 9999) {
        tx_log(TX_LOG_WARN, "[CM_OL_0004] 전문길이 범위오류 msglen=%ld", msglen);
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    tag = header_kind_tag(kind);
    if (strcmp(tag, "XX") == 0) {
        tx_log(TX_LOG_WARN, "[CM_OL_0004] 미정의 전문종별 kind=%s", kind);
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    /* 채널 마스터 조회 : 채널명/사용여부 확인 */
    strncpy(h_channel, channel, sizeof(h_channel) - 1);
    h_channel[sizeof(h_channel) - 1] = '\0';
    h_channel_nm[0] = '\0';
    strncpy(h_use_yn, "N", sizeof(h_use_yn));

    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select channel_nm , use_yn from cm_channel where channel_cd = $1 ", 
	ECPGt_char,(h_channel),(long)4,(long)1,(4)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, 
	ECPGt_char,(h_channel_nm),(long)40,(long)1,(40)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_char,(h_use_yn),(long)2,(long)1,(2)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT);}
#line 95 "app/online/cm_ol_0004.pgc"


    if (sqlca.sqlcode == TX_SQL_NOTFOUND) {
        tx_log(TX_LOG_WARN, "[CM_OL_0004] 미등록 채널 channel=%s", channel);
        tx_return(ctx, TX_ENOENT, ctx->out);
        return;
    }
    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("CM_OL_0004 SELECT cm_channel");
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }
    if (strcmp(h_use_yn, "Y") != 0) {
        tx_log(TX_LOG_WARN, "[CM_OL_0004] 미사용 채널 channel=%s", channel);
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    /* 표준 공통헤더 = 길이(4) + 종별태그(2) + 채널(2) + 거래일시(14) */
    snprintf(std_header, sizeof(std_header), "%04ld%2s%-2.2s%-14.14s",
             msglen, tag, channel, datetime);

    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "STDHEADER", std_header);
    tx_buf_setlong(ctx->out, "MSGLEN", msglen);
    tx_buf_sets(ctx->out, "KINDTAG", tag);
    tx_buf_sets(ctx->out, "CHANNELNM", h_channel_nm);
    tx_buf_setlong(ctx->out, "HDRLEN", (long)strlen(std_header));

    tx_log(TX_LOG_INFO, "[CM_OL_0004] 헤더조립 완료 tag=%s channel=%s(%s) header=[%s]",
           tag, channel, h_channel_nm, std_header);
    tx_return(ctx, TX_OK, ctx->out);
}
