/*
 * au_limit_reset_batch.pgc - au 일마감 한도 사용액 초기화 (커서 + dbio, XA).
 *
 * Cursor-scans every card_limit row and calls audb_limit_reset() on each under
 * ONE global XA transaction, zeroing daily used_amount. Usage: au_limit_reset_batch
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "au_dbio.h"

int main(int argc, char **argv)
{
    long rows = 0;

    EXEC SQL BEGIN DECLARE SECTION;
    char h_card[24];
    EXEC SQL END DECLARE SECTION;

    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 lrc CURSOR FOR SELECT card_no FROM card_limit WHERE used_amount > 0;
    EXEC SQL OPEN lrc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH lrc INTO :h_card;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE lrc; tpabort(0); return 1; }
        if (audb_limit_reset(h_card) < 0) { EXEC SQL CLOSE lrc; tpabort(0); return 1; }
        rows++;
    }
    EXEC SQL CLOSE lrc;

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

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