/*
 * rc_fxdiff_batch.pgc - 외화 환산 차이 배치 (커서 + XA): ac_fx 원화환산과 원통화*환율 이론치의 차이가 있는 건을 rc_diff 에 기록.
 * ATMI 클라이언트: tpinit/tpopen 으로 ECPG XA RM 를 열고 tpbegin 으로 ONE global tx
 * 를 시작, EXEC SQL 수행 후 tpcommit 이 XA 2PC 를 구동. 사용법: rc_fxdiff_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "rc_fxdiff_batch.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];
    long h_id, h_pid, h_krw, h_calc, h_diff;
    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 bcur CURSOR FOR
        SELECT purchase_id, krw_amount, fx_amount * rate_bps / 10000
        FROM ac_fx WHERE biz_date = :h_bizdate ORDER BY fx_id;
    EXEC SQL OPEN bcur;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH bcur INTO :h_pid, :h_krw, :h_calc;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE bcur; tpabort(0); return 1; }
        h_diff = h_krw - h_calc;
        if (h_diff == 0) continue;
        EXEC SQL SELECT nextval('rc_diff_seq') INTO :h_id;
        EXEC SQL INSERT INTO rc_diff (diff_id, purchase_id, expected_amt, actual_amt, diff_amt, diff_kind, biz_date)
            VALUES (:h_id, :h_pid, :h_calc, :h_krw, :h_diff, 'FX', :h_bizdate);
        if (sqlca.sqlcode < 0) { fprintf(stderr, "INS FAIL [%d]\n", sqlca.sqlcode); EXEC SQL CLOSE bcur; tpabort(0); return 1; }
        rows++;
    }
    EXEC SQL CLOSE bcur;

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

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