/*
 * au_limit_topup_batch.pgc - au 임시한도 정리 + 기본한도 상향 (다중 UPDATE, XA).
 *
 * Runs two sequential set UPDATEs (clear temp_limit, then top up daily_limit for
 * low-limit cards) under ONE global XA transaction. Usage: au_limit_topup_batch [DELTA]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "au_dbio.h"

int main(int argc, char **argv)
{
    long delta = (argc > 1) ? atol(argv[1]) : 500000;
    long cleared = 0, topped = 0;

    EXEC SQL BEGIN DECLARE SECTION;
    long h_delta;
    EXEC SQL END DECLARE SECTION;
    h_delta = delta;

    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 UPDATE card_limit SET temp_limit = 0, updated_at = now() WHERE temp_limit > 0;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "clear FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    cleared = sqlca.sqlerrd[2];

    EXEC SQL UPDATE card_limit SET daily_limit = daily_limit + :h_delta, updated_at = now()
        WHERE daily_limit < 1000000;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "topup FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    topped = sqlca.sqlerrd[2];

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> au_limit_topup_batch COMMIT: temp_cleared=%ld topped_up=%ld delta=%ld\n", cleared, topped, delta);

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