/*
 * py_xferconf_batch.pgc - py 이체 기표 일괄 확정 배치 (커서 + INSERT, XA).
 *
 * 당일 지급완료(P) 이면서 XFER 기표가 아직 없는 건을 NOT EXISTS 커서로 뽑아
 * py_ledger 에 net 만큼 XFER 기표를 일괄 생성한다. ONE XA txn.
 * host 변수는 전용 카피북 py_xferconf_cpy.h 를 EXEC SQL INCLUDE.
 * Usage: py_xferconf_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 posted = 0;

    EXEC SQL INCLUDE py_xferconf_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(120, 0) < 0) { fprintf(stderr, "tpbegin FAIL: %s\n", tpstrerror(tperrno)); return 1; }

    EXEC SQL DECLARE pxc CURSOR FOR
        SELECT payout_id, 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 payout_id;
    EXEC SQL OPEN pxc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH pxc INTO :c_pid, :c_net;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE pxc; 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, 'XFER', :c_net, :c_bizdate);
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE pxc; tpabort(0); return 1; }
        posted++;
    }
    EXEC SQL CLOSE pxc;

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