/*
 * au_card_dormant_batch.pgc - au 휴면 카드 일괄 표시 배치 (집합 UPDATE + XA).
 *
 * Counts, then set-updates every ACTIVE card with no authorization in the last
 * 90 days to status DORMANT in a single UPDATE, under one global XA transaction.
 * No cursor, no dbio. Usage: au_card_dormant_batch
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "au_dbio.h"
EXEC SQL INCLUDE au_card_dormant_batch;

int main(int argc, char **argv)
{
    EXEC SQL BEGIN DECLARE SECTION;
    long h_cand = 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_cand FROM card_limit
        WHERE status = 'ACTIVE'
          AND card_no NOT IN (SELECT DISTINCT card_no FROM au_authorization
                              WHERE created_at >= now() - interval '90 days');
    if (sqlca.sqlcode < 0) { fprintf(stderr, "SELECT FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }

    EXEC SQL UPDATE card_limit SET status = 'DORMANT', updated_at = now()
        WHERE status = 'ACTIVE'
          AND card_no NOT IN (SELECT DISTINCT card_no FROM au_authorization
                              WHERE created_at >= now() - interval '90 days');
    if (sqlca.sqlcode < 0) { fprintf(stderr, "UPDATE 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_card_dormant_batch COMMIT: dormant_marked=%ld\n", h_cand);

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