/* @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"

EXEC SQL INCLUDE sqlca;

#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;
        long h_rs_frag;
        long h_rs_merged;
        long h_rs_decl;
        EXEC SQL END DECLARE SECTION;

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

        if (tx_begin() == TX_OK) {
            EXEC SQL INSERT INTO mg_reasm_log
                (frag_cnt, merged_len, decl_len)
                VALUES (:h_rs_frag, :h_rs_merged, :h_rs_decl);
            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);
}
