/* @tier easy @module mm @transform master-batch */
/*
 * mm_bt_0008.pgc - 가맹점 마스터 검증배치 (MM_BT_0008)  [tier=easy]
 *
 * 유효 가맹점(mm_merchant) 을 커서로 순회하며 필수항목(정산계좌/사업자
 * 번호/수수료율) 누락 여부를 점검한다. 누락이 발견되면 결함내역
 * (mm_master_defect) 에 결함코드와 함께 INSERT 한다. 결함 건수를 집계한다.
 * 배치 main 엔트리 포함.
 *
 * 실행:  mm_bt_0008 <YYYYMMDD> [db@host]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

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

EXEC SQL INCLUDE sqlca;

static int run_mm_bt_0008(const char *biz_date)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_biz_date[9];
    char h_merch_id[16];
    char h_acct_no[24];
    char h_biz_reg_no[16];
    char h_defect_cd[8];
    long h_fee_rate;
    EXEC SQL END DECLARE SECTION;

    long total = 0, defect = 0, ok = 0, errcnt = 0;

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

    EXEC SQL DECLARE cur_mm_bt_0008 CURSOR FOR
        SELECT merch_id, acct_no, biz_reg_no, fee_rate
        FROM mm_merchant
        WHERE status = 'M'
        ORDER BY merch_id;

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

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

    for (;;) {
        EXEC SQL FETCH cur_mm_bt_0008
            INTO :h_merch_id, :h_acct_no, :h_biz_reg_no, :h_fee_rate;

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

        total++;

        /* 필수항목 결함코드 판정 (우선순위: 계좌 > 사업자번호 > 수수료율) */
        h_defect_cd[0] = '\0';
        if (strlen(h_acct_no) == 0)
            strncpy(h_defect_cd, "E-ACCT", sizeof(h_defect_cd));
        else if (strlen(h_biz_reg_no) < 10)
            strncpy(h_defect_cd, "E-BIZNO", sizeof(h_defect_cd));
        else if (h_fee_rate <= 0)
            strncpy(h_defect_cd, "E-FEE", sizeof(h_defect_cd));

        if (h_defect_cd[0] == '\0') {
            ok++;
            continue;
        }

        EXEC SQL INSERT INTO mm_master_defect
                     (merch_id, defect_cd, chk_date)
                 VALUES (:h_merch_id, :h_defect_cd, :h_biz_date);
        if (sqlca.sqlcode != TX_SQL_OK) {
            tx_log(TX_LOG_ERROR,
                   "[mm_bt_0008] 결함적재 실패 merch=%s cd=%s",
                   h_merch_id, h_defect_cd);
            errcnt++;
            continue;
        }

        defect++;
    }

    EXEC SQL CLOSE cur_mm_bt_0008;

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

    tx_log(TX_LOG_INFO,
           "[mm_bt_0008] 요약 date=%s 대상=%ld 정상=%ld 결함=%ld 오류=%ld",
           biz_date, total, ok, defect, errcnt);

    printf("========== 가맹점 마스터 검증배치 [mm_bt_0008] ==========\n");
    printf("  기준일       : %s\n", biz_date);
    printf("  검증 대상    : %ld\n", total);
    printf("  정상 건수    : %ld\n", ok);
    printf("  결함 검출    : %ld\n", defect);
    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, "[mm_bt_0008] 배치 시작 date=%s", biz_date);

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

    rc = run_mm_bt_0008(biz_date);

    mm_dbio_disconnect();

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