/*
 * py_xferrecon_batch.pgc - py 이체결과 대사 보정 배치 (안티조인 커서 + INSERT, XA).
 *
 * 당일 지급완료(P)인데 XFER 기표가 없는 건을 NOT EXISTS 커서로 찾아
 * py_ledger 에 XFERFIX 보정 기표를 채워 원장을 맞춘다.
 * host 변수는 전용 카피북 py_xferrecon_cpy.h 를 EXEC SQL INCLUDE.
 * Usage: py_xferrecon_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>

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

    EXEC SQL INCLUDE py_xferrecon_cpy;

    strncpy(c_bizdate, bizdate, sizeof(c_bizdate)-1); c_bizdate[sizeof(c_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(90, 0) < 0) { fprintf(stderr, "tpbegin FAIL: %s\n", tpstrerror(tperrno)); return 1; }

    EXEC SQL DECLARE pxr CURSOR FOR
        SELECT p.payout_id, p.net FROM py_payout p
         WHERE p.biz_date = :c_bizdate AND p.status = 'P'
           AND NOT EXISTS (SELECT 1 FROM py_ledger l
                            WHERE l.payout_id = p.payout_id AND l.entry_type = 'XFER')
         ORDER BY p.payout_id;
    EXEC SQL OPEN pxr;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH pxr INTO :c_pid, :c_net;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE pxr; tpabort(0); return 1; }
        EXEC SQL INSERT INTO py_ledger (ledger_id, payout_id, entry_type, amount, biz_date)
            VALUES (nextval('py_ledger_seq'), :c_pid, 'XFERFIX', :c_net, :c_bizdate);
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE pxr; tpabort(0); return 1; }
        fixed++; fixed_amt += c_net;
        printf("  [대사보정] payout=%ld XFERFIX %ld원 기표\n", c_pid, c_net);
    }
    EXEC SQL CLOSE pxr;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> py_xferrecon_batch COMMIT: bizdate=%s 보정기표=%ld건 %ld원\n", bizdate, fixed, fixed_amt);

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