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


#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_0023.pgc"


TX_SERVICE(MG_OL_0023, ctx)
{
    /* exec sql begin declare section */
     
     
     
     
    
#line 23 "app/online/mg_ol_0023.pgc"
 char h_token [ 33 ] ;
 
#line 24 "app/online/mg_ol_0023.pgc"
 char h_chan_cd [ 9 ] ;
 
#line 25 "app/online/mg_ol_0023.pgc"
 char h_status [ 2 ] ;
 
#line 26 "app/online/mg_ol_0023.pgc"
 char h_close_st [ 2 ] ;
/* exec sql end declare section */
#line 27 "app/online/mg_ol_0023.pgc"


    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) 현재 세션 상태 조회 */
    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select chan_cd , status from mg_chan where sess_token = $1 ", 
	ECPGt_char,(h_token),(long)33,(long)1,(33)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, 
	ECPGt_char,(h_chan_cd),(long)9,(long)1,(9)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_char,(h_status),(long)2,(long)1,(2)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT);}
#line 54 "app/online/mg_ol_0023.pgc"


    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 경고");

    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "update mg_chan set status = $1  , closed_ts = now ( ) where sess_token = $2 ", 
	ECPGt_char,(h_close_st),(long)2,(long)1,(2)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_char,(h_token),(long)33,(long)1,(33)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, ECPGt_EORT);}
#line 92 "app/online/mg_ol_0023.pgc"


    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);
}
