/*
 * au_capture_sweep_batch.pgc - au 승인 매입확정 스윕 (커서 + 인라인 UPDATE, XA).
 *
 * Cursor-scans approved(A) authorizations for a biz_date and flips each to
 * captured(M) with an inline EXEC SQL UPDATE inside the loop, all under ONE
 * global XA transaction. Usage: au_capture_sweep_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "au_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_auth;
    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 csc CURSOR FOR
        SELECT auth_id FROM au_authorization
        WHERE biz_date = :h_bizdate AND status = 'A' ORDER BY auth_id;
    EXEC SQL OPEN csc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH csc INTO :h_auth;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE csc; tpabort(0); return 1; }
        EXEC SQL UPDATE au_authorization SET status = 'M', captured_at = now(), updated_at = now()
            WHERE auth_id = :h_auth;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE csc; tpabort(0); return 1; }
        rows++;
    }
    EXEC SQL CLOSE csc;

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

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