/* @tier medium @module mm @transform master-batch */
/*
 * mm_bt_0005.pgc - 가맹점 등급 재산정 배치 (MM_BT_0005)  [tier=medium]
 *
 * 가맹점별 최근 3개월 누적매출(mm_merchant_sales) 을 커서로 집계하며,
 * 매출 규모 기준으로 등급(A/B/C) 을 재산정한다. 등급이 변경된 가맹점은
 * 원장(mm_merchant) 을 UPDATE 하고 등급변경이력(mm_grade_hist) 을
 * 남긴다. 배치 main 엔트리 포함.
 *
 * 실행:  mm_bt_0005 <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;

/* 등급 기준(원): A >= 3억, B >= 5천만, 그 외 C */
#define MM_GRADE_A_MIN  300000000L
#define MM_GRADE_B_MIN   50000000L

static int run_mm_bt_0005(const char *biz_date)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_biz_date[9];
    char h_merch_id[16];
    char h_old_grade[2];
    char h_new_grade[2];
    long h_sale_sum;
    EXEC SQL END DECLARE SECTION;

    long total = 0, changed = 0, kept = 0, errcnt = 0;

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

    /* 최근 3개월 매출을 가맹점 단위로 집계 */
    EXEC SQL DECLARE cur_mm_bt_0005 CURSOR FOR
        SELECT s.merch_id, m.grade, SUM(s.sale_amt)
        FROM mm_merchant_sales s
        JOIN mm_merchant m ON m.merch_id = s.merch_id
        WHERE s.sale_ym >= :h_biz_date
          AND m.status  = 'M'
        GROUP BY s.merch_id, m.grade
        ORDER BY s.merch_id;

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

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

    for (;;) {
        EXEC SQL FETCH cur_mm_bt_0005
            INTO :h_merch_id, :h_old_grade, :h_sale_sum;

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

        total++;

        /* 매출 규모 → 신규 등급 */
        if (h_sale_sum >= MM_GRADE_A_MIN)
            strncpy(h_new_grade, "A", sizeof(h_new_grade));
        else if (h_sale_sum >= MM_GRADE_B_MIN)
            strncpy(h_new_grade, "B", sizeof(h_new_grade));
        else
            strncpy(h_new_grade, "C", sizeof(h_new_grade));

        if (strcmp(h_new_grade, h_old_grade) == 0) {
            kept++;
            continue;
        }

        EXEC SQL UPDATE mm_merchant
                    SET grade      = :h_new_grade,
                        grade_date = :h_biz_date
                  WHERE merch_id = :h_merch_id;
        if (sqlca.sqlcode != TX_SQL_OK) {
            tx_log(TX_LOG_ERROR,
                   "[mm_bt_0005] 등급갱신 실패 merch=%s", h_merch_id);
            errcnt++;
            continue;
        }

        EXEC SQL INSERT INTO mm_grade_hist
                     (merch_id, old_grade, new_grade, sale_sum, chg_date)
                 VALUES (:h_merch_id, :h_old_grade, :h_new_grade,
                         :h_sale_sum, :h_biz_date);

        changed++;
    }

    EXEC SQL CLOSE cur_mm_bt_0005;

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

    tx_log(TX_LOG_INFO,
           "[mm_bt_0005] 요약 date=%s 대상=%ld 변경=%ld 유지=%ld 오류=%ld",
           biz_date, total, changed, kept, errcnt);

    printf("========== 가맹점 등급 재산정 [mm_bt_0005] ==========\n");
    printf("  기준일       : %s\n", biz_date);
    printf("  평가 대상    : %ld\n", total);
    printf("  등급 변경    : %ld\n", changed);
    printf("  등급 유지    : %ld\n", kept);
    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_0005] 배치 시작 date=%s", biz_date);

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

    rc = run_mm_bt_0005(biz_date);

    mm_dbio_disconnect();

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