/* @tier medium @module mg @transform msg-gateway-online */
/*
 * mg_ol_0005.pgc - 전문 로깅/추적 서비스 (MG_OL_0005)  [tier=medium]
 *
 * 거래추적번호(STAN)/채널(CHAN)/전문종별(MSGTYPE)로 추적로그 항목을
 * 구성하여 tx_log 로 기록하고, 추적테이블(mg_stat)에 EXEC SQL 로 적재한다.
 * 채널+STAN 조합으로 추적키를 만들어 응답한다.
 */
#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;

TX_SERVICE(MG_OL_0005, ctx)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_trkey[32];
    char h_chan[16];
    char h_stan[12];
    char h_mtype[8];
    long h_xid;
    EXEC SQL END DECLARE SECTION;

    char chan[16];
    char stan[12];
    char mtype[8];
    char trkey[32];

    tx_log(TX_LOG_INFO, "[MG_OL_0005] 전문 추적로그 서비스 진입");

    /* 1) 추적 3요소 수신 */
    if (tx_buf_get(ctx->in, "CHAN", chan, sizeof(chan)) != TX_OK ||
        tx_buf_get(ctx->in, "STAN", stan, sizeof(stan)) != TX_OK ||
        tx_buf_get(ctx->in, "MSGTYPE", mtype, sizeof(mtype)) != TX_OK ||
        chan[0] == '\0' || stan[0] == '\0') {
        tx_log(TX_LOG_ERROR, "[MG_OL_0005] 추적요소(CHAN/STAN/MSGTYPE) 누락");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    /* 2) 추적키 = 채널#STAN */
    snprintf(trkey, sizeof(trkey), "%s#%s", chan, stan);

    /* 3) 구조화 추적로그 기록 */
    tx_log(TX_LOG_INFO, "[MG_OL_0005] TRACE chan=%s stan=%s type=%s trkey=%s",
           chan, stan, mtype, trkey);

    /* 4) 추적테이블 적재 */
    strncpy(h_trkey, trkey, sizeof(h_trkey) - 1);  h_trkey[sizeof(h_trkey) - 1] = '\0';
    strncpy(h_chan,  chan,  sizeof(h_chan)  - 1);  h_chan[sizeof(h_chan)   - 1] = '\0';
    strncpy(h_stan,  stan,  sizeof(h_stan)  - 1);  h_stan[sizeof(h_stan)   - 1] = '\0';
    strncpy(h_mtype, mtype, sizeof(h_mtype) - 1);  h_mtype[sizeof(h_mtype) - 1] = '\0';
    h_xid = tx_current_xid();

    EXEC SQL INSERT INTO mg_stat
        (trace_key, chan_id, stan, msg_type, xid, log_ts)
        VALUES (:h_trkey, :h_chan, :h_stan, :h_mtype, :h_xid, now());

    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("MG_OL_0005 mg_stat insert");
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESP", RESP_SYSERR);
        tx_buf_sets(ctx->out, "TRKEY", trkey);
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }

    /* 5) 추적키 응답 */
    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "RESP", RESP_OK);
    tx_buf_sets(ctx->out, "TRKEY", trkey);
    tx_buf_sets(ctx->out, "CHAN", chan);
    tx_buf_sets(ctx->out, "STAN", stan);
    tx_buf_setlong(ctx->out, "XID", h_xid);
    tx_log(TX_LOG_INFO, "[MG_OL_0005] 추적로그 적재완료 trkey=%s xid=%ld", trkey, h_xid);
    tx_return(ctx, TX_OK, ctx->out);
}
