/*
 * py_schedule_run_batch.pgc - py 예약 지급 실행 (커서 + dbio + inline UPDATE, XA).
 *
 * Cursors the day's pending(S) schedules; per row it flips the linked payout to
 * requested(R) via dbio and marks the schedule done(D) inline, under ONE XA
 * transaction. Usage: py_schedule_run_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "py_dbio.h"

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

    EXEC SQL BEGIN DECLARE SECTION;
    char h_rundate[16];
    long h_sched, h_pay;
    EXEC SQL END DECLARE SECTION;

    strncpy(h_rundate, rundate, sizeof(h_rundate)-1); h_rundate[sizeof(h_rundate)-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 pyrsc CURSOR FOR
        SELECT schedule_id, payout_id FROM py_schedule
        WHERE run_date = :h_rundate AND status = 'S'
        ORDER BY schedule_id;
    EXEC SQL OPEN pyrsc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH pyrsc INTO :h_sched, :h_pay;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE pyrsc; tpabort(0); return 1; }
        if (pydb_update_status(h_pay, "R") < 0) { EXEC SQL CLOSE pyrsc; tpabort(0); return 1; }
        EXEC SQL UPDATE py_schedule SET status = 'D' WHERE schedule_id = :h_sched;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE pyrsc; tpabort(0); return 1; }
        rows++;
    }
    EXEC SQL CLOSE pyrsc;

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

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