/*
 * au_whitelist_clean_batch.pgc - au 만료 폐기토큰 블랙 정리 배치 (집합 DELETE + XA).
 *
 * Counts, then set-deletes TOKEN_REVOKED blacklist rows older than 30 days in a
 * single DELETE (auto-whitelisting expired revocations), under one global XA
 * transaction. No cursor. Usage: au_whitelist_clean_batch
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "au_dbio.h"
EXEC SQL INCLUDE au_whitelist_clean_batch;

int main(int argc, char **argv)
{
    EXEC SQL BEGIN DECLARE SECTION;
    long h_stale = 0;
    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 SELECT count(*) INTO :h_stale FROM au_blacklist
        WHERE reason = 'TOKEN_REVOKED' AND created_at < now() - interval '30 days';
    if (sqlca.sqlcode < 0) { fprintf(stderr, "SELECT FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }

    EXEC SQL DELETE FROM au_blacklist
        WHERE reason = 'TOKEN_REVOKED' AND created_at < now() - interval '30 days';
    if (sqlca.sqlcode < 0) { fprintf(stderr, "DELETE FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }

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

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