/*
 * rc_fxrecon_batch.pgc - 외화 대사 배치 (커서 + XA).
 * 당일 외화 거래(ac_fx)를 매입과 조인해 원화환산 금액이 매입 금액과 다른
 * 건을 커서로 순회, 건별로 통화코드를 담은 대사 예외를 적재한다.
 * 사용법: rc_fxrecon_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "rc_dbio.h"
#include "rc_fxrecon_batch.h"

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

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_ccy[8], h_reason[48];
    long h_pid, h_krw, h_amt;
    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 cxb CURSOR FOR
        SELECT f.purchase_id, f.ccy, f.krw_amount, p.amount
        FROM ac_fx f, purchase p
        WHERE f.purchase_id = p.purchase_id AND f.biz_date = :h_bizdate
          AND f.krw_amount <> p.amount
        ORDER BY f.fx_id;
    EXEC SQL OPEN cxb;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH cxb INTO :h_pid, :h_ccy, :h_krw, :h_amt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE cxb; tpabort(0); return 1; }
        rec.pid = h_pid; rec.krw = h_krw; rec.amount = h_amt;
        strncpy(rec.ccy, h_ccy, sizeof(rec.ccy)-1); rec.ccy[sizeof(rec.ccy)-1] = 0;
        snprintf(h_reason, sizeof(h_reason), "FX KRW MISMATCH %.4s", rec.ccy);
        EXEC SQL INSERT INTO rc_exception (exc_id, purchase_id, reason, biz_date)
            VALUES (nextval('rc_exc_seq'), :h_pid, :h_reason, :h_bizdate);
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE cxb; tpabort(0); return 1; }
        excs++;
    }
    EXEC SQL CLOSE cxb;

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

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