/* 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_0020.pgc"
/* @tier medium @module mg @transform msg-gateway-online */
/*
 * mg_ol_0020.pgc - 전문게이트웨이 전문 순번(STAN) 채번 서비스 (MG_OL_0020)  [tier=medium]
 *
 * 채널/기관 단위 시퀀스행(mg_seq)을 원자적으로 증가시켜 6자리 STAN
 * (System Trace Audit Number)을 채번한다. raw EXEC SQL 로 UPDATE ...
 * SET seq_val = seq_val + 1 후 증가값을 SELECT 하며, 000001~999999 를
 * 순환(랩어라운드)한다. 시퀀스행이 없으면 최초 1 로 생성한다.
 */
#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_0020.pgc"


#define STAN_MAX 999999

TX_SERVICE(MG_OL_0020, ctx)
{
    /* exec sql begin declare section */
     
     
     
    
#line 25 "app/online/mg_ol_0020.pgc"
 char h_seqname [ 16 ] ;
 
#line 26 "app/online/mg_ol_0020.pgc"
 long h_seqval ;
 
#line 27 "app/online/mg_ol_0020.pgc"
 long h_stanmax ;
/* exec sql end declare section */
#line 28 "app/online/mg_ol_0020.pgc"


    char seqname[16];
    char stan[8];
    long stanval;

    tx_log(TX_LOG_INFO, "[MG_OL_0020] STAN 채번 서비스 진입");

    if (tx_buf_get(ctx->in, "SEQNAME", seqname, sizeof(seqname)) != TX_OK ||
        seqname[0] == '\0') {
        tx_log(TX_LOG_ERROR, "[MG_OL_0020] 시퀀스명(SEQNAME) 누락");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }
    strncpy(h_seqname, seqname, sizeof(h_seqname) - 1);
    h_seqname[sizeof(h_seqname) - 1] = '\0';
    h_stanmax = STAN_MAX;

    if (tx_begin() != TX_OK) {
        tx_return(ctx, TX_FAIL, ctx->out);
        return;
    }

    /* 원자적 증가 (랩어라운드는 갱신식 내에서 처리) */
    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "update mg_seq set seq_val = ( case when seq_val >= $1  then 1 else seq_val + 1 end ) , upd_ts = now ( ) where seq_name = $2 ", 
	ECPGt_long,&(h_stanmax),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_char,(h_seqname),(long)16,(long)1,(16)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, ECPGt_EORT);}
#line 56 "app/online/mg_ol_0020.pgc"

    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("MG_OL_0020 mg_seq update");
        tx_abort();
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }

    /* 대상행이 없으면 최초 1 로 생성 */
    if (sqlca.sqlerrd[2] == 0) {
        h_seqval = 1;
        { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "insert into mg_seq ( seq_name , seq_val , upd_ts ) values ( $1  , $2  , now ( ) )", 
	ECPGt_char,(h_seqname),(long)16,(long)1,(16)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_seqval),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, ECPGt_EORT);}
#line 68 "app/online/mg_ol_0020.pgc"

        if (sqlca.sqlcode != TX_SQL_OK) {
            TX_DBIO_LOG_ERR("MG_OL_0020 mg_seq insert");
            tx_abort();
            tx_return(ctx, TX_EDB, ctx->out);
            return;
        }
        tx_log(TX_LOG_INFO, "[MG_OL_0020] 시퀀스 신규생성 name=%s", seqname);
    }

    /* 증가 결과 조회 */
    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select seq_val from mg_seq where seq_name = $1 ", 
	ECPGt_char,(h_seqname),(long)16,(long)1,(16)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, 
	ECPGt_long,&(h_seqval),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT);}
#line 82 "app/online/mg_ol_0020.pgc"

    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("MG_OL_0020 mg_seq select");
        tx_abort();
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }

    tx_commit();

    stanval = h_seqval;
    if (stanval < 1 || stanval > STAN_MAX)
        stanval = ((stanval - 1) % STAN_MAX) + 1;
    snprintf(stan, sizeof(stan), "%06ld", stanval);

    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "RESPCODE", RESP_OK);
    tx_buf_sets(ctx->out, "SEQNAME", seqname);
    tx_buf_sets(ctx->out, "STAN", stan);
    tx_buf_setlong(ctx->out, "SEQVAL", stanval);
    tx_log(TX_LOG_INFO, "[MG_OL_0020] STAN 채번완료 name=%s stan=%s", seqname, stan);
    tx_return(ctx, TX_OK, ctx->out);
}
