/* @tier medium @module mg @transform msg-gateway-online */
/*
 * mg_ol_0023.pgc - 전문게이트웨이 채널 세션 종료 서비스 (MG_OL_0023)  [tier=medium]
 *
 * 채널이 보유한 세션토큰(SESSTOKEN)을 검증한 뒤, 채널 세션 테이블
 * (mg_chan)의 상태를 종료('C')로 전이시킨다. 이미 종료되었거나 존재하지
 * 않는 세션은 반려하고, 정상 종료 시 종료결과를 응답한다.
 * (ATMI void SVC(TPSVCINFO*) 대응)
 */
#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_0023, ctx)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_token[33];
    char h_chan_cd[9];
    char h_status[2];
    char h_close_st[2];
    EXEC SQL END DECLARE SECTION;

    char token[33];

    tx_log(TX_LOG_INFO, "[MG_OL_0023] 채널 세션 종료 서비스 진입");

    /* 1) 세션토큰 수신/검증 */
    if (tx_buf_get(ctx->in, "SESSTOKEN", token, sizeof(token)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[MG_OL_0023] 세션토큰(SESSTOKEN) 누락");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }
    if (strlen(token) < 8) {
        tx_log(TX_LOG_WARN, "[MG_OL_0023] 세션토큰 길이 오류 len=%d", (int)strlen(token));
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESP", RESP_INVALID);
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    strncpy(h_token, token, sizeof(h_token) - 1);
    h_token[sizeof(h_token) - 1] = '\0';

    /* 2) 현재 세션 상태 조회 */
    EXEC SQL
        SELECT chan_cd, status INTO :h_chan_cd, :h_status
          FROM mg_chan
         WHERE sess_token = :h_token;

    if (sqlca.sqlcode == TX_SQL_NOTFOUND) {
        tx_log(TX_LOG_WARN, "[MG_OL_0023] 세션 없음 token=%.8s...", token);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESP", RESP_INVALID);
        tx_return(ctx, TX_ENOENT, ctx->out);
        return;
    }
    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("SELECT mg_chan(세션조회)");
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESP", RESP_SYSERR);
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }

    /* 3) 이미 종료된 세션은 멱등 반려 */
    if (h_status[0] == 'C') {
        tx_log(TX_LOG_INFO, "[MG_OL_0023] 이미 종료된 세션 chan=%s", h_chan_cd);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESP", RESP_OK);
        tx_buf_sets(ctx->out, "CHANCD", h_chan_cd);
        tx_buf_sets(ctx->out, "CLOSED", "N");
        tx_return(ctx, TX_OK, ctx->out);
        return;
    }

    /* 4) 세션 종료 상태 전이 */
    strncpy(h_close_st, "C", sizeof(h_close_st));

    if (tx_begin() != TX_OK)
        tx_log(TX_LOG_WARN, "[MG_OL_0023] tx_begin 경고");

    EXEC SQL
        UPDATE mg_chan
           SET status = :h_close_st,
               closed_ts = now()
         WHERE sess_token = :h_token;

    if (sqlca.sqlcode != TX_SQL_OK || sqlca.sqlerrd[2] != 1) {
        TX_DBIO_LOG_ERR("UPDATE mg_chan(세션종료)");
        tx_abort();
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESP", RESP_SYSERR);
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }

    tx_commit();

    /* 5) 종료결과 응답 */
    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "RESP", RESP_OK);
    tx_buf_sets(ctx->out, "CHANCD", h_chan_cd);
    tx_buf_sets(ctx->out, "CLOSED", "Y");
    tx_log(TX_LOG_INFO, "[MG_OL_0023] 세션 종료완료 chan=%s token=%.8s...",
           h_chan_cd, token);
    tx_return(ctx, TX_OK, ctx->out);
}
