/*
 * rc_feerecon_batch.pgc - 수수료 대사 배치 (커서 + XA).
 * 당일 매입을 가맹점 MDR 과 조인해 기대 수수료와 다른 건을 커서로 순회하며
 * 건별 rc_diff 금액 차이 라인을 적재한다. 하나의 글로벌 트랜잭션으로 2PC.
 * 사용법: rc_feerecon_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "rc_dbio.h"
#include "rc_feerecon_batch.h"

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

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_pid, h_fee, h_exp;
    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 cfb CURSOR FOR
        SELECT p.purchase_id, p.fee, p.amount * m.mdr_bps / 10000
        FROM purchase p, merchant m
        WHERE p.merchant_id = m.merchant_id AND p.biz_date = :h_bizdate
          AND p.fee <> p.amount * m.mdr_bps / 10000
        ORDER BY p.purchase_id;
    EXEC SQL OPEN cfb;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH cfb INTO :h_pid, :h_fee, :h_exp;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE cfb; tpabort(0); return 1; }
        rec.pid = h_pid; rec.fee = h_fee; rec.expected = h_exp;
        EXEC SQL INSERT INTO rc_diff
            (diff_id, purchase_id, expected_amt, actual_amt, diff_amt, diff_kind, biz_date)
            VALUES (nextval('rc_diff_seq'), :h_pid, :h_exp, :h_fee, :h_fee - :h_exp,
                    'AMT', :h_bizdate);
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE cfb; tpabort(0); return 1; }
        diffs++;
    }
    EXEC SQL CLOSE cfb;

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

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