/* 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/batch/cm_bt_0012.pgc"
/* @tier easy @module cm @transform common-batch */
/*
 * cm_bt_0012.pgc - 공통 영업일자 롤오버 배치  [tier=easy]
 *
 * 시스템 공통 파라미터(cm_param)의 현재 영업일(BIZ_DATE)을 조회하여
 * date_next_business 로 다음 영업일을 산출한 뒤 파라미터를 갱신한다.
 * 인자로 받은 기준일과 현재 영업일의 일치 여부도 점검한다.
 * 배치 main 엔트리 포함.
 *
 * 실행:  cm_bt_0012 <YYYYMMDD> [db@host]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "txcore.h"
#include "txcore_dbio.h"
#include "acq_util.h"
#include "cm_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 21 "app/batch/cm_bt_0012.pgc"


static int run_cm_bt_0012(const char *biz_date)
{
    /* exec sql begin declare section */
     
     
    
#line 26 "app/batch/cm_bt_0012.pgc"
 char h_cur_date [ 9 ] ;
 
#line 27 "app/batch/cm_bt_0012.pgc"
 char h_next_date [ 9 ] ;
/* exec sql end declare section */
#line 28 "app/batch/cm_bt_0012.pgc"


    char next_date[9];

    /* 1) 현재 영업일 파라미터 조회 */
    memset(h_cur_date, 0, sizeof(h_cur_date));
    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select param_val from cm_param where param_key = 'BIZ_DATE'", ECPGt_EOIT, 
	ECPGt_char,(h_cur_date),(long)9,(long)1,(9)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT);}
#line 36 "app/batch/cm_bt_0012.pgc"


    if (sqlca.sqlcode == TX_SQL_NOTFOUND) {
        tx_log(TX_LOG_ERROR, "[cm_bt_0012] BIZ_DATE 파라미터 없음");
        return TX_ENOENT;
    }
    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("SELECT cm_param BIZ_DATE");
        return TX_EDB;
    }

    /* 2) 기준일 정합성 점검 (경고만) */
    if (strncmp(h_cur_date, biz_date, 8) != 0)
        tx_log(TX_LOG_WARN, "[cm_bt_0012] 기준일 불일치 param=%s arg=%s",
               h_cur_date, biz_date);

    /* 3) 다음 영업일 산출 */
    memset(next_date, 0, sizeof(next_date));
    if (date_next_business(h_cur_date, next_date) != 0) {
        tx_log(TX_LOG_ERROR, "[cm_bt_0012] 다음영업일 계산 실패 cur=%s", h_cur_date);
        return TX_FAIL;
    }

    memset(h_next_date, 0, sizeof(h_next_date));
    strncpy(h_next_date, next_date, sizeof(h_next_date) - 1);

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

    /* 4) 영업일 파라미터 갱신 */
    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "update cm_param set param_val = $1  , upd_ts = current_timestamp where param_key = 'BIZ_DATE'", 
	ECPGt_char,(h_next_date),(long)9,(long)1,(9)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, ECPGt_EORT);}
#line 69 "app/batch/cm_bt_0012.pgc"


    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("UPDATE cm_param BIZ_DATE");
        tx_abort();
        return TX_EDB;
    }
    tx_commit();

    tx_log(TX_LOG_INFO, "[cm_bt_0012] 영업일 롤오버 %s -> %s", h_cur_date, next_date);

    printf("========== 영업일자 롤오버 [cm_bt_0012] ==========\n");
    printf("  이전 영업일 : %s\n", h_cur_date);
    printf("  신규 영업일 : %s\n", next_date);
    printf("=============================================\n");

    return TX_OK;
}

int main(int argc, char **argv)
{
    const char *biz_date;
    const char *target;
    int rc;

    tx_set_loglevel(TX_LOG_INFO);

    if (argc < 2) {
        fprintf(stderr, "사용법: %s <YYYYMMDD> [db@host]\n", argv[0]);
        return 2;
    }
    biz_date = argv[1];
    target   = (argc >= 3) ? argv[2] : NULL;

    if (!date_is_valid(biz_date)) {
        fprintf(stderr, "오류: 유효하지 않은 영업일 '%s'\n", biz_date);
        return 2;
    }

    tx_log(TX_LOG_INFO, "[cm_bt_0012] 롤오버 배치 시작 date=%s", biz_date);

    rc = cm_dbio_connect(target);
    if (rc != TX_OK) {
        tx_log(TX_LOG_ERROR, "[cm_bt_0012] DB 접속 실패 rc=%d", rc);
        return 1;
    }

    rc = run_cm_bt_0012(biz_date);

    cm_dbio_disconnect();

    tx_log(TX_LOG_INFO, "[cm_bt_0012] 배치 종료 rc=%d(%s)", rc, tx_strerror(rc));
    return (rc == TX_OK) ? 0 : 1;
}
