/* 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/mg_bt_0016.pgc"
/* @tier medium @module mg @transform msg-gateway-batch */
/*
 * mg_bt_0016.pgc - 전문게이트웨이 채널 헬스체크 집계 배치  [tier=medium]
 *
 * 채널 상태 테이블(mg_chan)을 커서로 순회하며 채널별 헬스 응답률(성공/총
 * 요청)을 계산하고, 임계(95%) 미만 채널을 비정상으로 분류·집계한다.
 * 배치 main 엔트리 포함.
 *
 * 실행:  mg_bt_0016 <YYYYMMDD> [db@host]
 */
#include <stdio.h>
#include <stdlib.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 20 "app/batch/mg_bt_0016.pgc"


#define MG_HEALTH_THRESHOLD 95   /* 정상 판정 응답률(%) */

static int run_mg_bt_0016(void)
{
    /* exec sql begin declare section */
     
     
     
    
#line 27 "app/batch/mg_bt_0016.pgc"
 char h_chan_cd [ 8 ] ;
 
#line 28 "app/batch/mg_bt_0016.pgc"
 long h_req ;
 
#line 29 "app/batch/mg_bt_0016.pgc"
 long h_ok ;
/* exec sql end declare section */
#line 30 "app/batch/mg_bt_0016.pgc"


    long chans = 0, healthy = 0, unhealthy = 0, idle = 0;

    /* declare cur_mg_bt_0016 cursor for select chan_cd , coalesce ( req_cnt , 0 ) , coalesce ( ok_cnt , 0 ) from mg_chan order by chan_cd */
#line 37 "app/batch/mg_bt_0016.pgc"


    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "declare cur_mg_bt_0016 cursor for select chan_cd , coalesce ( req_cnt , 0 ) , coalesce ( ok_cnt , 0 ) from mg_chan order by chan_cd", ECPGt_EOIT, ECPGt_EORT);}
#line 39 "app/batch/mg_bt_0016.pgc"

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

    for (;;) {
        long rate;

        { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "fetch cur_mg_bt_0016", ECPGt_EOIT, 
	ECPGt_char,(h_chan_cd),(long)8,(long)1,(8)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_req),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_ok),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT);}
#line 48 "app/batch/mg_bt_0016.pgc"


        if (sqlca.sqlcode == TX_SQL_NOTFOUND)
            break;
        if (sqlca.sqlcode != TX_SQL_OK) {
            TX_DBIO_LOG_ERR("FETCH cur_mg_bt_0016");
            break;
        }

        chans++;

        if (h_req <= 0) {
            idle++;
            tx_log(TX_LOG_DEBUG, "[mg_bt_0016] 유휴채널 chan=%s", h_chan_cd);
            continue;
        }

        rate = (h_ok * 100) / h_req;
        if (rate >= MG_HEALTH_THRESHOLD) {
            healthy++;
        } else {
            unhealthy++;
            tx_log(TX_LOG_WARN, "[mg_bt_0016] 비정상 채널 chan=%s 응답률=%ld%%",
                   h_chan_cd, rate);
        }
    }

    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "close cur_mg_bt_0016", ECPGt_EOIT, ECPGt_EORT);}
#line 75 "app/batch/mg_bt_0016.pgc"


    tx_log(TX_LOG_INFO,
           "[mg_bt_0016] 헬스집계 채널=%ld 정상=%ld 비정상=%ld 유휴=%ld",
           chans, healthy, unhealthy, idle);

    printf("========== 채널 헬스체크 집계 [mg_bt_0016] ==========\n");
    printf("  총 채널수   : %ld\n", chans);
    printf("  정상 채널   : %ld\n", healthy);
    printf("  비정상 채널 : %ld\n", unhealthy);
    printf("  유휴 채널   : %ld\n", idle);
    printf("=============================================\n");

    return (unhealthy == 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, "[mg_bt_0016] 헬스체크 배치 시작 date=%s", biz_date);

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

    rc = run_mg_bt_0016();

    mg_dbio_disconnect();

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