/*
 * st_retrorate_batch.pgc - 요율 소급적용 배치 (조인 커서 + 행별 조정 + XA).
 * 당일 MDR 정산 상세를 매입 금액과 조인 순회하며 신규 bps 로 재계산, 기계상
 * 수수료와의 차액을 건별 소급 조정으로 기록한다. 사용법: st_retrorate_batch [YYYY-MM-DD] [bps]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "st_dbio.h"
#include "st_retrorate_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    st_retrorate_rec_t rec;
    memset(&rec, 0, sizeof(rec));
    rec.new_bps = (argc > 2) ? atol(argv[2]) : ST_RETRORATE_DEF_BPS;

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_sid, h_pid, h_old, 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 retro_bc CURSOR FOR
        SELECT d.settlement_id, d.purchase_id, d.amount, p.amount
        FROM st_settle_dtl d JOIN purchase p ON p.purchase_id = d.purchase_id
        WHERE d.biz_date = :h_bizdate AND d.fee_type = 'MDR';
    EXEC SQL OPEN retro_bc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH retro_bc INTO :h_sid, :h_pid, :h_old, :h_amount;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE retro_bc; tpabort(0); return 1; }
        {
            long newfee = h_amount * rec.new_bps / 10000;
            long diff = newfee - h_old;
            if (diff == 0) continue;
            if (stdb_insert_adjust(h_sid, h_pid, diff, "RETRO_RATE", bizdate) < 0) { EXEC SQL CLOSE retro_bc; tpabort(0); return 1; }
            rec.adjusted++;
            rec.delta_sum += diff;
        }
    }
    EXEC SQL CLOSE retro_bc;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> %s COMMIT: bizdate=%s new_bps=%ld adjusted=%ld delta_sum=%ld\n",
           ST_RETRORATE_TAG, bizdate, rec.new_bps, rec.adjusted, rec.delta_sum);

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