/* @tier easy @module cm @transform common-online */
/*
 * cm_ol_0012.pgc - 코드 변환(내부→대외) 서비스 (CM_OL_0012)  [tier=easy]
 *
 * 요청의 원천시스템(SRCSYS)/내부코드(SRCCD) 로 코드매핑 마스터
 * (cm_code_map)를 조회하여 대외 표준코드(대상시스템/대상코드/대상명)를
 * 응답 TXBUF 로 반환한다. 대외기관 연계용 코드 변환 게이트웨이.
 * (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"

EXEC SQL INCLUDE sqlca;

TX_SERVICE(CM_OL_0012, ctx)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_src_sys[16];
    char h_src_cd[16];
    char h_dst_sys[16];
    char h_dst_cd[20];
    char h_dst_name[64];
    EXEC SQL END DECLARE SECTION;

    char src_sys[16];
    char src_cd[16];

    tx_log(TX_LOG_INFO, "[CM_OL_0012] 코드 변환 서비스 진입");

    if (tx_buf_get(ctx->in, "SRCSYS", src_sys, sizeof(src_sys)) != TX_OK ||
        tx_buf_get(ctx->in, "SRCCD",  src_cd,  sizeof(src_cd))  != TX_OK) {
        tx_log(TX_LOG_ERROR, "[CM_OL_0012] SRCSYS/SRCCD 누락");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    memset(h_src_sys,  0, sizeof(h_src_sys));
    memset(h_src_cd,   0, sizeof(h_src_cd));
    memset(h_dst_sys,  0, sizeof(h_dst_sys));
    memset(h_dst_cd,   0, sizeof(h_dst_cd));
    memset(h_dst_name, 0, sizeof(h_dst_name));
    strncpy(h_src_sys, src_sys, sizeof(h_src_sys) - 1);
    strncpy(h_src_cd,  src_cd,  sizeof(h_src_cd) - 1);

    EXEC SQL
        SELECT dst_sys, dst_cd, dst_name
          INTO :h_dst_sys, :h_dst_cd, :h_dst_name
          FROM cm_code_map
         WHERE src_sys = :h_src_sys
           AND src_cd  = :h_src_cd
           AND use_yn  = 'Y';

    if (sqlca.sqlcode == TX_SQL_NOTFOUND) {
        tx_log(TX_LOG_WARN, "[CM_OL_0012] 매핑 없음 sys=%s cd=%s", src_sys, src_cd);
        tx_return(ctx, TX_ENOENT, ctx->out);
        return;
    }
    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("CM_OL_0012 SELECT cm_code_map");
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }

    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "SRCSYS", src_sys);
    tx_buf_sets(ctx->out, "SRCCD",  src_cd);
    tx_buf_sets(ctx->out, "DSTSYS", h_dst_sys);
    tx_buf_sets(ctx->out, "DSTCD",  h_dst_cd);
    tx_buf_sets(ctx->out, "DSTNAME", h_dst_name);
    tx_log(TX_LOG_INFO, "[CM_OL_0012] 변환완료 %s:%s -> %s:%s",
           src_sys, src_cd, h_dst_sys, h_dst_cd);
    tx_return(ctx, TX_OK, ctx->out);
}
