/* 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_0022.pgc"
/* @tier medium @module mg @transform msg-gateway-online */
/*
 * mg_ol_0022.pgc - 전문게이트웨이 분할전문 재조립 서비스 (MG_OL_0022)  [tier=medium]
 *
 * 대용량 전문을 분할 전송한 조각(FRAG00~FRAGnn)을 순서대로 병합해 원본
 * 전문을 복원한다. 요청은 총조각수(TOTAL)와 각 조각(FRAGnn), 무결성용
 * 총길이(TOTLEN)를 포함하며, 조각 결번/누락을 검증하고 병합 후 실제
 * 길이와 선언 길이를 대조하여 완성전문(FULLMSG)을 응답한다.
 */
#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 18 "app/online/mg_ol_0022.pgc"


#define MAX_FRAG   32
#define FULL_MAX   512

TX_SERVICE(MG_OL_0022, ctx)
{
    char full[FULL_MAX];
    char frag[128];
    char fkey[12];
    long total = 0;
    long totlen = 0;
    int  filled = 0;
    int  merged_len = 0;
    int  i;

    tx_log(TX_LOG_INFO, "[MG_OL_0022] 분할전문 재조립 서비스 진입");

    if (tx_buf_getlong(ctx->in, "TOTAL", &total) != TX_OK || total <= 0) {
        tx_log(TX_LOG_ERROR, "[MG_OL_0022] 총조각수(TOTAL) 누락/오류");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }
    if (total > MAX_FRAG) {
        tx_log(TX_LOG_WARN, "[MG_OL_0022] 조각수 초과 total=%ld max=%d", total, MAX_FRAG);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_INVALID);
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }
    tx_buf_getlong(ctx->in, "TOTLEN", &totlen);

    memset(full, 0, sizeof(full));

    /* 조각을 SEQ 오름차순(0..TOTAL-1)으로 순서검증하며 병합 */
    for (i = 0; i < (int)total; i++) {
        snprintf(fkey, sizeof(fkey), "FRAG%02d", i);
        if (tx_buf_get(ctx->in, fkey, frag, sizeof(frag)) != TX_OK) {
            tx_log(TX_LOG_ERROR, "[MG_OL_0022] 조각 결번 seq=%d key=%s", i, fkey);
            tx_buf_reset(ctx->out);
            tx_buf_sets(ctx->out, "RESPCODE", RESP_INVALID);
            tx_buf_setlong(ctx->out, "MISSINGSEQ", (long)i);
            tx_return(ctx, TX_FAIL, ctx->out);
            return;
        }
        {
            int flen = (int)strlen(frag);
            if (merged_len + flen >= FULL_MAX) {
                tx_log(TX_LOG_ERROR, "[MG_OL_0022] 재조립 버퍼 초과 at seq=%d", i);
                tx_buf_reset(ctx->out);
                tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
                tx_return(ctx, TX_FAIL, ctx->out);
                return;
            }
            memcpy(full + merged_len, frag, flen);
            merged_len += flen;
        }
        filled++;
    }
    full[merged_len] = '\0';

    /* 무결성 대조: 조각수 일치 + 선언 총길이 일치 */
    if (filled != (int)total) {
        tx_log(TX_LOG_WARN, "[MG_OL_0022] 조각수 불일치 filled=%d total=%ld", filled, total);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_INVALID);
        tx_return(ctx, TX_FAIL, ctx->out);
        return;
    }
    if (totlen > 0 && totlen != (long)merged_len) {
        tx_log(TX_LOG_WARN, "[MG_OL_0022] 총길이 불일치 decl=%ld merged=%d",
               totlen, merged_len);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_INVALID);
        tx_buf_setlong(ctx->out, "MERGEDLEN", (long)merged_len);
        tx_return(ctx, TX_FAIL, ctx->out);
        return;
    }

    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "RESPCODE", RESP_OK);
    tx_buf_sets(ctx->out, "FULLMSG", full);
    tx_buf_setlong(ctx->out, "FRAGCNT", (long)filled);
    tx_buf_setlong(ctx->out, "MERGEDLEN", (long)merged_len);

    /* 재조립 이력(mg_reasm_log)을 임베디드 SQL 로 적재 */
    {
        /* exec sql begin declare section */
         
         
         
        
#line 106 "app/online/mg_ol_0022.pgc"
 long h_rs_frag ;
 
#line 107 "app/online/mg_ol_0022.pgc"
 long h_rs_merged ;
 
#line 108 "app/online/mg_ol_0022.pgc"
 long h_rs_decl ;
/* exec sql end declare section */
#line 109 "app/online/mg_ol_0022.pgc"


        h_rs_frag   = (long)filled;
        h_rs_merged = (long)merged_len;
        h_rs_decl   = totlen;

        if (tx_begin() == TX_OK) {
            { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "insert into mg_reasm_log ( frag_cnt , merged_len , decl_len ) values ( $1  , $2  , $3  )", 
	ECPGt_long,&(h_rs_frag),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_rs_merged),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_rs_decl),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, ECPGt_EORT);}
#line 118 "app/online/mg_ol_0022.pgc"

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

    tx_log(TX_LOG_INFO, "[MG_OL_0022] 재조립 완료 조각=%d 길이=%d", filled, merged_len);
    tx_return(ctx, TX_OK, ctx->out);
}
