/*
 * au_token_revoke_batch.pgc - au 폐기 토큰 카드 원장 표시 배치 (커서 + XA).
 *
 * Cursor-scans TOKEN_REVOKED blacklist rows (card + reason) and marks each
 * card_limit row REVOKED with an inner UPDATE, under one global XA transaction.
 * Usage: au_token_revoke_batch
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "au_dbio.h"
EXEC SQL INCLUDE au_token_revoke_batch;

int main(int argc, char **argv)
{
    long seen = 0, marked = 0;
    EXEC SQL BEGIN DECLARE SECTION;
    char h_card[24], h_reason[64];
    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 trv CURSOR FOR
        SELECT card_no, reason FROM au_blacklist
        WHERE reason = 'TOKEN_REVOKED' ORDER BY created_at;
    EXEC SQL OPEN trv;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH trv INTO :h_card, :h_reason;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d]\n", sqlca.sqlcode); EXEC SQL CLOSE trv; tpabort(0); return 1; }
        EXEC SQL UPDATE card_limit SET status = 'REVOKED', updated_at = now()
            WHERE card_no = :h_card AND status <> 'REVOKED';
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE trv; tpabort(0); return 1; }
        if (sqlca.sqlcode != 100) marked++;
        seen++;
    }
    EXEC SQL CLOSE trv;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> au_token_revoke_batch COMMIT: revoked_tokens=%ld cards_marked=%ld\n", seen, marked);

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