/*
 * st_rateapply_batch.pgc - st 구간요율 적용 산출 (조인 커서 + XA).
 *
 * st_settle_dtl 을 st_fee_rate 와 구간(band_min) 조인 커서로 순회하며 요율 적용액을
 * 누계한다. 하나의 글로벌 트랜잭션에서 조회 후 2PC 커밋. 사용법: st_rateapply_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "st_dbio.h"
#include "st_rateapply_batch.h"

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

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_ft[16];
    long h_amt, h_bps;
    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 rac CURSOR FOR
        SELECT d.fee_type, d.amount, r.rate_bps
        FROM st_settle_dtl d
        JOIN st_fee_rate r ON r.fee_type = d.fee_type AND d.amount >= r.band_min
        WHERE d.biz_date = :h_bizdate ORDER BY d.dtl_id;
    EXEC SQL OPEN rac;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH rac INTO :h_ft, :h_amt, :h_bps;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE rac; tpabort(0); return 1; }
        strncpy(rec.fee_type, h_ft, sizeof(rec.fee_type)-1); rec.fee_type[sizeof(rec.fee_type)-1] = 0;
        rec.amt = h_amt; rec.bps = h_bps;
        total += rec.amt * rec.bps / 10000;
        lines++;
    }
    EXEC SQL CLOSE rac;

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

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