/*
 * au_reproc_queue_batch.pgc - au 보류 승인 재처리 큐 배치 (커서 + dbio + XA).
 *
 * Cursor-scans the day's HELD (H) authorizations and re-approves each by driving
 * the dbio status transition to A, under one global XA transaction.
 * Usage: au_reproc_queue_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "au_dbio.h"
EXEC SQL INCLUDE au_reproc_queue_batch;

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 rpq CURSOR FOR
        SELECT auth_id FROM au_authorization
        WHERE biz_date = :h_bizdate AND status = 'H' ORDER BY auth_id;
    EXEC SQL OPEN rpq;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH rpq INTO :h_auth;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d]\n", sqlca.sqlcode); EXEC SQL CLOSE rpq; tpabort(0); return 1; }
        if (audb_update_auth_status(h_auth, "A") < 0) { EXEC SQL CLOSE rpq; tpabort(0); return 1; }
        rows++;
    }
    EXEC SQL CLOSE rpq;

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

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