/*
 * st_feecalc_batch.pgc - st 수수료 계산 배치 (커서 + XA).
 *
 * 당일 정산 각 건에 대해 매입 금액 기준 구간요율(dbio)을 적용해 MDR 수수료를
 * 계산하고 st_settle_dtl 에 정산 상세를 (dbio 로) 기록한다 (ONE global XA tx).
 * 사용법: st_feecalc_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "st_dbio.h"
#include "acq_common.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    long rows = 0;

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_merch[64];
    long h_sid, h_pid, h_amount;
    EXEC SQL END DECLARE SECTION;

    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;

    if (tpinit(NULL) < 0) { fprintf(stderr, "tpinit FAIL: %s\n", tpstrerror(tperrno)); return 1; }
    if (tpopen() < 0)     { fprintf(stderr, "tpopen FAIL: %s\n", tpstrerror(tperrno)); return 1; }
    if (tpbegin(60, 0) < 0) { fprintf(stderr, "tpbegin FAIL: %s\n", tpstrerror(tperrno)); return 1; }

    EXEC SQL DECLARE sfc CURSOR FOR
        SELECT s.settlement_id, s.purchase_id, s.merchant_id, p.amount
        FROM settlement s JOIN purchase p ON p.purchase_id = s.purchase_id
        WHERE s.biz_date = :h_bizdate
        ORDER BY s.settlement_id;
    EXEC SQL OPEN sfc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        long bps, fee;
        EXEC SQL FETCH sfc INTO :h_sid, :h_pid, :h_merch, :h_amount;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE sfc; tpabort(0); return 1; }
        bps = stdb_lookup_rate("MDR", h_amount);
        if (bps < 0) { EXEC SQL CLOSE sfc; tpabort(0); return 1; }
        fee = acq_fee(h_amount, bps);
        if (stdb_insert_fee_dtl(h_sid, h_pid, h_merch, "MDR", fee, bizdate) < 0) {
            EXEC SQL CLOSE sfc; tpabort(0); return 1;
        }
        rows++;
    }
    EXEC SQL CLOSE sfc;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> st_feecalc_batch COMMIT: bizdate=%s fee_rows=%ld\n", bizdate, rows);

    tpclose(); tpterm();
    return 0;
}
