/* 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/vl_bt_0016.pgc"
/* @tier easy @module vl @transform validation-batch */
/*
 * vl_bt_0016.pgc - 정합성 통계 집계 배치 (VL_BT_0016)  [tier=easy]
 *
 * 지정 영업일의 정합성 처리 결과를 표준 DBIO 집계 API(vl_rec_count/
 * vl_rec_sum) 로 산출하여, 일별 통계 테이블(vl_stat_daily) 에 대상/정합/
 * 불일치/거래금액과 영업일 구분(영업일/휴일) 을 INSERT 한다. 기존 통계가
 * 있으면 재적재를 위해 선삭제(UPSERT) 한다. 배치 main 엔트리 포함.
 *
 * 실행:  vl_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 "vl_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/vl_bt_0016.pgc"


static int run_vl_bt_0016(const char *biz_date)
{
    /* exec sql begin declare section */
     
     
     
     
     
     
        /* 'B'=영업일, 'H'=휴일 */
    
#line 26 "app/batch/vl_bt_0016.pgc"
 char h_biz_date [ 9 ] ;
 
#line 27 "app/batch/vl_bt_0016.pgc"
 long h_target ;
 
#line 28 "app/batch/vl_bt_0016.pgc"
 long h_matched ;
 
#line 29 "app/batch/vl_bt_0016.pgc"
 long h_mismatch ;
 
#line 30 "app/batch/vl_bt_0016.pgc"
 long h_settled ;
 
#line 31 "app/batch/vl_bt_0016.pgc"
 long h_amount_sum ;
 
#line 32 "app/batch/vl_bt_0016.pgc"
 char h_day_type [ 2 ] ;
/* exec sql end declare section */
#line 33 "app/batch/vl_bt_0016.pgc"


    long recv;
    int  errcnt = 0;
    int  rc;

    strncpy(h_biz_date, biz_date, sizeof(h_biz_date) - 1);
    h_biz_date[sizeof(h_biz_date) - 1] = '\0';

    /* 표준 집계 API 로 상태별 건수/금액 산출 */
    recv         = vl_rec_count(biz_date, VL_ST_RECV);
    h_matched    = vl_rec_count(biz_date, VL_ST_DONE);
    h_mismatch   = vl_rec_count(biz_date, VL_ST_FAIL);
    h_settled    = vl_rec_count(biz_date, VL_ST_SETTLED);
    h_target     = recv + h_matched + h_mismatch + h_settled;

    h_amount_sum = 0;
    rc = vl_rec_sum(biz_date, &h_amount_sum);
    if (rc != TX_OK) {
        tx_log(TX_LOG_WARN, "[vl_bt_0016] 금액합 조회 경고 rc=%d", rc);
        h_amount_sum = 0;
    }

    /* 영업일 구분 */
    if (date_is_weekend(biz_date))
        strncpy(h_day_type, "H", sizeof(h_day_type));
    else
        strncpy(h_day_type, "B", sizeof(h_day_type));

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

    /* 재적재: 기존 통계 선삭제 후 INSERT */
    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "delete from vl_stat_daily where stat_date = $1 ", 
	ECPGt_char,(h_biz_date),(long)9,(long)1,(9)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, ECPGt_EORT);}
#line 66 "app/batch/vl_bt_0016.pgc"

    if (sqlca.sqlcode != TX_SQL_OK && sqlca.sqlcode != TX_SQL_NOTFOUND) {
        TX_DBIO_LOG_ERR("DELETE vl_stat_daily");
        errcnt++;
    }

    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "insert into vl_stat_daily ( stat_date , day_type , target_cnt , matched_cnt , mismatch_cnt , settled_cnt , amount_sum ) values ( $1  , $2  , $3  , $4  , $5  , $6  , $7  )", 
	ECPGt_char,(h_biz_date),(long)9,(long)1,(9)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_char,(h_day_type),(long)2,(long)1,(2)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_target),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_matched),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_mismatch),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_settled),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_amount_sum),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, ECPGt_EORT);}
#line 77 "app/batch/vl_bt_0016.pgc"

    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("INSERT vl_stat_daily");
        errcnt++;
    }

    if (errcnt == 0)
        tx_commit();
    else
        tx_abort();

    tx_log(TX_LOG_INFO,
           "[vl_bt_0016] 요약 date=%s 대상=%ld 정합=%ld 불일치=%ld 금액=%ld 오류=%d",
           biz_date, h_target, h_matched, h_mismatch, h_amount_sum, errcnt);

    printf("========== 정합성 통계 집계 [vl_bt_0016] ==========\n");
    printf("  영업일        : %s (%s)\n", biz_date,
           (h_day_type[0] == 'H') ? "휴일" : "영업일");
    printf("  대상 건수     : %ld\n", h_target);
    printf("  정합(M)       : %ld\n", h_matched);
    printf("  불일치(U)     : %ld\n", h_mismatch);
    printf("  정산완료(S)   : %ld\n", h_settled);
    printf("  거래금액 합계 : %ld\n", h_amount_sum);
    printf("  vl_stat_daily : 적재 %s\n", (errcnt == 0) ? "성공" : "실패");
    printf("  오류 건수     : %d\n", errcnt);
    printf("================================================\n");

    return (errcnt == 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, "[vl_bt_0016] 배치 시작 date=%s", biz_date);

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

    rc = run_vl_bt_0016(biz_date);

    vl_dbio_disconnect();

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