/*
 * au_stolen_sweep_batch.pgc - au 도난/분실 카드 잔여승인 정리 배치 (커서 + XA).
 *
 * Cursor-scans blacklist entries flagged STOLEN/LOST and cancels each card's
 * still-open (A/H) authorizations with an inner UPDATE, under one global XA
 * transaction. Usage: au_stolen_sweep_batch
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "au_dbio.h"
EXEC SQL INCLUDE au_stolen_sweep_batch;

int main(int argc, char **argv)
{
    long cards = 0, cancelled = 0;
    EXEC SQL BEGIN DECLARE SECTION;
    char h_card[24];
    EXEC SQL END DECLARE SECTION;

    (void)argc; (void)argv;
    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 ssw CURSOR FOR
        SELECT card_no FROM au_blacklist WHERE reason IN ('STOLEN','LOST') ORDER BY card_no;
    EXEC SQL OPEN ssw;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH ssw INTO :h_card;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d]\n", sqlca.sqlcode); EXEC SQL CLOSE ssw; tpabort(0); return 1; }
        EXEC SQL UPDATE au_authorization SET status = 'C', updated_at = now()
            WHERE card_no = :h_card AND status IN ('A','H');
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE ssw; tpabort(0); return 1; }
        if (sqlca.sqlcode != 100) cancelled++;
        cards++;
    }
    EXEC SQL CLOSE ssw;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> au_stolen_sweep_batch COMMIT: cards=%ld cancelled_batches=%ld\n", cards, cancelled);

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