/*
 * py_adjust_apply_batch.pgc - py 조정 반영 (커서 + inline UPDATE, XA).
 *
 * Cursors the day's adjustments and applies each delta to the linked payout's
 * net with an inline UPDATE, under ONE XA transaction.
 * Usage: py_adjust_apply_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 *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    long rows = 0;

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_pay, h_delta;
    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 pyaac CURSOR FOR
        SELECT payout_id, delta FROM py_adjust WHERE biz_date = :h_bizdate ORDER BY adj_id;
    EXEC SQL OPEN pyaac;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH pyaac INTO :h_pay, :h_delta;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE pyaac; tpabort(0); return 1; }
        EXEC SQL UPDATE py_payout SET net = net + :h_delta, updated_at = now() WHERE payout_id = :h_pay;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE pyaac; tpabort(0); return 1; }
        rows++;
    }
    EXEC SQL CLOSE pyaac;

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

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