/* 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_0013.pgc"
/* @tier easy @module cm @transform common-batch */
/*
 * cm_bt_0013.pgc - 공통 캐시 정합성 점검 배치  [tier=easy]
 *
 * 공통코드 마스터(cm_code)와 코드 매핑(cm_code_map)의 건수를 각각 단건
 * 집계로 조회하여, 매핑이 참조하는 코드 대비 마스터 코드 규모를 대조하고
 * 고아 매핑 가능성을 판정·리포트한다. 배치 main 엔트리 포함.
 *
 * 실행:  cm_bt_0013 <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 20 "app/batch/cm_bt_0013.pgc"


static int run_cm_bt_0013(void)
{
    /* exec sql begin declare section */
     
     
     
     
    
#line 25 "app/batch/cm_bt_0013.pgc"
 long h_code_cnt ;
 
#line 26 "app/batch/cm_bt_0013.pgc"
 long h_active_cnt ;
 
#line 27 "app/batch/cm_bt_0013.pgc"
 long h_map_cnt ;
 
#line 28 "app/batch/cm_bt_0013.pgc"
 long h_orphan_cnt ;
/* exec sql end declare section */
#line 29 "app/batch/cm_bt_0013.pgc"


    h_code_cnt = h_active_cnt = h_map_cnt = h_orphan_cnt = 0;

    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select count ( * ) from cm_code", ECPGt_EOIT, 
	ECPGt_long,&(h_code_cnt),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT);}
#line 33 "app/batch/cm_bt_0013.pgc"

    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("COUNT cm_code");
        return TX_EDB;
    }

    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select count ( * ) from cm_code where use_yn = 'Y'", ECPGt_EOIT, 
	ECPGt_long,&(h_active_cnt),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT);}
#line 40 "app/batch/cm_bt_0013.pgc"

    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("COUNT cm_code active");
        return TX_EDB;
    }

    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select count ( * ) from cm_code_map", ECPGt_EOIT, 
	ECPGt_long,&(h_map_cnt),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT);}
#line 46 "app/batch/cm_bt_0013.pgc"

    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("COUNT cm_code_map");
        return TX_EDB;
    }

    /* 매핑의 원천코드가 마스터에 없는 고아 매핑 수 */
    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select count ( * ) from cm_code_map m where not exists ( select 1 from cm_code c where c . grp_cd = m . src_grp and c . code_cd = m . src_cd )", ECPGt_EOIT, 
	ECPGt_long,&(h_orphan_cnt),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT);}
#line 58 "app/batch/cm_bt_0013.pgc"

    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("COUNT orphan");
        return TX_EDB;
    }

    tx_log(TX_LOG_INFO,
           "[cm_bt_0013] 캐시점검 코드=%ld 활성=%ld 매핑=%ld 고아=%ld",
           h_code_cnt, h_active_cnt, h_map_cnt, h_orphan_cnt);

    if (h_orphan_cnt > 0)
        tx_log(TX_LOG_WARN, "[cm_bt_0013] 고아 매핑 %ld건 발견 - 캐시 재적재 권고",
               h_orphan_cnt);

    printf("========== 캐시 정합성 점검 [cm_bt_0013] ==========\n");
    printf("  전체 코드   : %ld\n", h_code_cnt);
    printf("  활성 코드   : %ld\n", h_active_cnt);
    printf("  코드 매핑   : %ld\n", h_map_cnt);
    printf("  고아 매핑   : %ld\n", h_orphan_cnt);
    printf("  정합 여부   : %s\n", (h_orphan_cnt == 0) ? "정상" : "불일치");
    printf("=============================================\n");

    return (h_orphan_cnt == 0) ? TX_OK : TX_FAIL;
}

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_0013] 캐시점검 배치 시작 date=%s", biz_date);

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

    rc = run_cm_bt_0013();

    cm_dbio_disconnect();

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