/* @tier hard @module lg @transform ledger-batch */
/*
 * lg_bt_0002.pgc - 정산원장 반영 배치 (완료건 정산전이 + 정산액 집계)  [tier=hard]
 *
 * 지정 영업일의 처리완료(status='M') 원장을 커서로 순회하며 각 건을
 * 정산완료('S')로 전이하고, 정산액/수수료를 누계하여 요약을 출력한다.
 *
 * 실행:  lg_bt_0002 <YYYYMMDD> [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"

EXEC SQL INCLUDE sqlca;

static int run_lg_bt_0002(const char *biz_date)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_biz_date[9];
    char h_key[16];
    long h_amount;
    long h_fee;
    EXEC SQL END DECLARE SECTION;

    long total = 0, settled = 0, errcnt = 0;
    long sum_settle = 0, sum_fee = 0;
    char won[32];
    int  rc;

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

    EXEC SQL DECLARE cur_lg_bt_0002 CURSOR FOR
        SELECT key, amount, fee
        FROM lg_ledger
        WHERE biz_date = :h_biz_date
          AND status   = 'M'
        ORDER BY key;

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

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

    for (;;) {
        EXEC SQL FETCH cur_lg_bt_0002 INTO :h_key, :h_amount, :h_fee;

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

        total++;

        rc = lg_rec_update_status(h_key, LG_ST_SETTLED);
        if (rc != TX_OK) {
            tx_log(TX_LOG_ERROR, "[lg_bt_0002] 정산전이 실패 key=%s rc=%d", h_key, rc);
            errcnt++;
            continue;
        }
        settled++;
        sum_settle += h_amount;
        sum_fee    += h_fee;
    }

    EXEC SQL CLOSE cur_lg_bt_0002;

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

    amount_format_won(sum_settle, won, sizeof(won));

    tx_log(TX_LOG_INFO,
           "[lg_bt_0002] 요약 date=%s 대상=%ld 정산=%ld 정산액=%ld 오류=%ld",
           biz_date, total, settled, sum_settle, errcnt);

    printf("========== 정산원장 반영 결과 [lg_bt_0002] ==========\n");
    printf("  영업일        : %s\n", biz_date);
    printf("  대상(M) 건수  : %ld\n", total);
    printf("  정산(S) 건수  : %ld\n", settled);
    printf("  정산액 합계   : %s\n", won);
    printf("  수수료 합계   : %ld\n", sum_fee);
    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, "[lg_bt_0002] 배치 시작 date=%s", biz_date);

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

    rc = run_lg_bt_0002(biz_date);

    lg_dbio_disconnect();

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