/* 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/lg_bt_0012.pgc"
/* @tier easy @module lg @transform ledger-batch */
/*
 * lg_bt_0012.pgc - diff 검증 배치 (두 영업일 대비)  [tier=easy]
 *
 * 인자로 받은 두 영업일 D1, D2 각각의 건수/거래금액 합계를 SELECT 하여
 * 두 일자 간 차이를 리포트한다. 인자 3개(프로그램명 포함)를 요구한다.
 *
 * 실행:  lg_bt_0012 <YYYYMMDD_D1> <YYYYMMDD_D2> [db@host]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "txcore.h"
#include "txcore_dbio.h"
#include "acq_util.h"
#include "lg_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 19 "app/batch/lg_bt_0012.pgc"


static int run_lg_bt_0012(const char *d1, const char *d2)
{
    /* exec sql begin declare section */
     
     
     
    
#line 24 "app/batch/lg_bt_0012.pgc"
 char h_date [ 9 ] ;
 
#line 25 "app/batch/lg_bt_0012.pgc"
 long h_cnt ;
 
#line 26 "app/batch/lg_bt_0012.pgc"
 long h_sum ;
/* exec sql end declare section */
#line 27 "app/batch/lg_bt_0012.pgc"


    long cnt1 = 0, cnt2 = 0, sum1 = 0, sum2 = 0;
    long dcnt, dsum;
    char won1[32], won2[32], wond[32];

    /* D1 집계 */
    strncpy(h_date, d1, sizeof(h_date) - 1);
    h_date[sizeof(h_date) - 1] = '\0';
    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select count ( * ) , coalesce ( sum ( amount ) , 0 ) from lg_ledger where biz_date = $1 ", 
	ECPGt_char,(h_date),(long)9,(long)1,(9)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, 
	ECPGt_long,&(h_cnt),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_sum),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT);}
#line 39 "app/batch/lg_bt_0012.pgc"

    if (sqlca.sqlcode != TX_SQL_OK && sqlca.sqlcode != TX_SQL_NOTFOUND) {
        TX_DBIO_LOG_ERR("SELECT D1 lg_bt_0012");
        return TX_EDB;
    }
    cnt1 = h_cnt;
    sum1 = h_sum;

    /* D2 집계 */
    strncpy(h_date, d2, sizeof(h_date) - 1);
    h_date[sizeof(h_date) - 1] = '\0';
    { ECPGdo(__LINE__, 0, 1, NULL, 0, ECPGst_normal, "select count ( * ) , coalesce ( sum ( amount ) , 0 ) from lg_ledger where biz_date = $1 ", 
	ECPGt_char,(h_date),(long)9,(long)1,(9)*sizeof(char), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EOIT, 
	ECPGt_long,&(h_cnt),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, 
	ECPGt_long,&(h_sum),(long)1,(long)1,sizeof(long), 
	ECPGt_NO_INDICATOR, NULL , 0L, 0L, 0L, ECPGt_EORT);}
#line 53 "app/batch/lg_bt_0012.pgc"

    if (sqlca.sqlcode != TX_SQL_OK && sqlca.sqlcode != TX_SQL_NOTFOUND) {
        TX_DBIO_LOG_ERR("SELECT D2 lg_bt_0012");
        return TX_EDB;
    }
    cnt2 = h_cnt;
    sum2 = h_sum;

    dcnt = cnt2 - cnt1;
    dsum = sum2 - sum1;

    amount_format_won(sum1, won1, sizeof(won1));
    amount_format_won(sum2, won2, sizeof(won2));
    amount_format_won(dsum, wond, sizeof(wond));

    tx_log(TX_LOG_INFO,
           "[lg_bt_0012] diff D1=%s(%ld/%ld) D2=%s(%ld/%ld) Δ건수=%ld Δ금액=%ld",
           d1, cnt1, sum1, d2, cnt2, sum2, dcnt, dsum);

    printf("========== 원장 diff 검증 결과 [lg_bt_0012] ==========\n");
    printf("  기준일 D1 : %s  건수=%ld  금액=%s\n", d1, cnt1, won1);
    printf("  비교일 D2 : %s  건수=%ld  금액=%s\n", d2, cnt2, won2);
    printf("  ----------------------------------------------\n");
    printf("  건수 차이(D2-D1) : %ld\n", dcnt);
    printf("  금액 차이(D2-D1) : %s\n", wond);
    printf("  판정             : %s\n",
           (dcnt == 0 && dsum == 0) ? "동일" : "차이 있음");
    printf("==================================================\n");

    return TX_OK;
}

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

    tx_set_loglevel(TX_LOG_INFO);

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

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

    tx_log(TX_LOG_INFO, "[lg_bt_0012] 배치 시작 D1=%s D2=%s", d1, d2);

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

    rc = run_lg_bt_0012(d1, d2);

    lg_dbio_disconnect();

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