/* @tier easy @module ac @transform acquire-batch */
/*
 * ac_bt_0007.pgc - 카드사별 매입분류 배치  [tier=easy]
 *
 * 지정 영업일 전체 매입 건을 커서로 순회하며 카드번호 BIN 앞 2자리로
 * 카드사(corp_cd) 를 판별하여 매입원장에 반영한다.
 * ('94'=KB, '95'=SH, '96'=HN, 그 외=ETC). 배치 main 엔트리 포함.
 *
 * 실행:  ac_bt_0007 <YYYYMMDD> [db@host]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "txcore.h"
#include "txcore_dbio.h"
#include "acq_util.h"
#include "ac_core.h"

EXEC SQL INCLUDE sqlca;

static int run_ac_bt_0007(const char *biz_date)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_biz_date[9];
    char h_key[16];
    char h_card_no[20];
    char h_corp_cd[4];
    EXEC SQL END DECLARE SECTION;

    long total = 0, errcnt = 0;
    long cnt_kb = 0, cnt_sh = 0, cnt_hn = 0, cnt_etc = 0;
    char bin2[3];

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

    EXEC SQL DECLARE cur_ac_bt_0007 CURSOR FOR
        SELECT key, card_no
        FROM ac_ledger
        WHERE biz_date = :h_biz_date
        ORDER BY key;

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

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

    for (;;) {
        EXEC SQL FETCH cur_ac_bt_0007 INTO :h_key, :h_card_no;

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

        total++;

        /* 업무규칙: 카드번호 BIN 앞 2자리로 카드사 판별 */
        bin2[0] = h_card_no[0];
        bin2[1] = h_card_no[1];
        bin2[2] = '\0';

        if (strcmp(bin2, "94") == 0) {
            strncpy(h_corp_cd, "KB", sizeof(h_corp_cd));
            cnt_kb++;
        } else if (strcmp(bin2, "95") == 0) {
            strncpy(h_corp_cd, "SH", sizeof(h_corp_cd));
            cnt_sh++;
        } else if (strcmp(bin2, "96") == 0) {
            strncpy(h_corp_cd, "HN", sizeof(h_corp_cd));
            cnt_hn++;
        } else {
            strncpy(h_corp_cd, "ETC", sizeof(h_corp_cd));
            cnt_etc++;
        }
        h_corp_cd[sizeof(h_corp_cd) - 1] = '\0';

        EXEC SQL UPDATE ac_ledger
            SET corp_cd = :h_corp_cd
            WHERE key = :h_key;

        if (sqlca.sqlcode != TX_SQL_OK) {
            TX_DBIO_LOG_ERR("UPDATE cur_ac_bt_0007");
            tx_log(TX_LOG_ERROR, "[ac_bt_0007] 분류 반영 실패 key=%s", h_key);
            errcnt++;
            continue;
        }
        if (sqlca.sqlerrd[2] == 0) {
            tx_log(TX_LOG_WARN, "[ac_bt_0007] 대상없음 key=%s", h_key);
            errcnt++;
        }
    }

    EXEC SQL CLOSE cur_ac_bt_0007;

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

    tx_log(TX_LOG_INFO,
           "[ac_bt_0007] 요약 date=%s 대상=%ld KB=%ld SH=%ld HN=%ld ETC=%ld 오류=%ld",
           biz_date, total, cnt_kb, cnt_sh, cnt_hn, cnt_etc, errcnt);

    printf("========== 카드사별 매입분류 결과 [ac_bt_0007] ==========\n");
    printf("  영업일      : %s\n", biz_date);
    printf("  대상 건수   : %ld\n", total);
    printf("  KB          : %ld\n", cnt_kb);
    printf("  SH          : %ld\n", cnt_sh);
    printf("  HN          : %ld\n", cnt_hn);
    printf("  ETC         : %ld\n", cnt_etc);
    printf("  오류 건수   : %ld\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, "[ac_bt_0007] 배치 시작 date=%s", biz_date);

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

    rc = run_ac_bt_0007(biz_date);

    ac_dbio_disconnect();

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