/*
 * au_preauth_convert_batch.pgc - au 만기 선승인 처분 배치 (커서 + 방침 분기, XA).
 *
 * 기준일 이전에 잡힌 미확정(P) 선승인을 커서로 훑어 방침에 따라 처분한다:
 * 고액(문턱 이상)은 자동확정(C)해 승인 파이프라인으로 넘기고, 나머지는
 * 자동취소(X)로 홀드를 해제하며 풀린 금액을 적산한다. ONE XA transaction.
 * Usage: au_preauth_convert_batch [기준일 YYYY-MM-DD] [확정문턱금액]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "au_preauth_convert_batch.h"

int aub_preauth_should_confirm(long amount, long threshold)
{
    return (amount >= threshold) ? 1 : 0;
}

int main(int argc, char **argv)
{
    au_preauth_convert_ctx_t ctx;
    const char *cutoff = (argc > 1) ? argv[1] : "2026-07-12";
    long threshold = (argc > 2) ? atol(argv[2]) : 500000;

    EXEC SQL BEGIN DECLARE SECTION;
    char h_cutoff[16];
    long h_pid, h_amt;
    EXEC SQL END DECLARE SECTION;

    memset(&ctx, 0, sizeof(ctx));
    strncpy(ctx.cutoff_date, cutoff, sizeof(ctx.cutoff_date)-1);
    if (threshold <= 0) threshold = 500000;
    strncpy(h_cutoff, cutoff, sizeof(h_cutoff)-1); h_cutoff[sizeof(h_cutoff)-1] = 0;

    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(120, 0) < 0) { fprintf(stderr, "tpbegin FAIL: %s\n", tpstrerror(tperrno)); return 1; }

    EXEC SQL DECLARE cpcb CURSOR FOR
        SELECT preauth_id, amount FROM au_preauth
        WHERE status = 'P' AND biz_date < :h_cutoff
        ORDER BY preauth_id;
    EXEC SQL OPEN cpcb;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH cpcb INTO :h_pid, :h_amt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE cpcb; tpabort(0); return 1; }

        if (aub_preauth_should_confirm(h_amt, threshold)) {
            EXEC SQL UPDATE au_preauth SET status = 'C' WHERE preauth_id = :h_pid;
            if (sqlca.sqlcode < 0) { EXEC SQL CLOSE cpcb; tpabort(0); return 1; }
            ctx.confirmed++;
        } else {
            EXEC SQL UPDATE au_preauth SET status = 'X' WHERE preauth_id = :h_pid;
            if (sqlca.sqlcode < 0) { EXEC SQL CLOSE cpcb; tpabort(0); return 1; }
            ctx.expired++;
            ctx.released_amount += h_amt;
        }
    }
    EXEC SQL CLOSE cpcb;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> au_preauth_convert_batch COMMIT: cutoff=%s 자동확정=%ld 자동취소=%ld 해제금액=%ld (문턱=%ld)\n",
           ctx.cutoff_date, ctx.confirmed, ctx.expired, ctx.released_amount, threshold);

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