/*
 * au_standin_settle_batch.pgc - au 대행승인 정산반영 배치 (커서 + 개별 UPDATE, XA).
 *
 * 이슈어 장애 복구 후 실행: 영업일의 STANDIN 승인(A) 건을 커서로 돌며
 * 건별 검증(금액>0) 후 정산반영(S)으로 전환하고 건수/금액을 적산한다.
 * ONE global XA transaction 으로 전량 원자 반영.
 * Usage: au_standin_settle_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "au_standin_settle_batch.h"

int aub_standin_any(const au_standin_settle_ctx_t *ctx)
{
    return (ctx->settled > 0) ? 1 : 0;
}

int main(int argc, char **argv)
{
    au_standin_settle_ctx_t ctx;
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_auth, h_amt;
    EXEC SQL END DECLARE SECTION;

    memset(&ctx, 0, sizeof(ctx));
    strncpy(ctx.biz_date, bizdate, sizeof(ctx.biz_date)-1);
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-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 cssb CURSOR FOR
        SELECT auth_id, amount FROM au_authorization
        WHERE biz_date = :h_bizdate AND auth_type = 'STANDIN' AND status = 'A'
        ORDER BY auth_id;
    EXEC SQL OPEN cssb;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH cssb INTO :h_auth, :h_amt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE cssb; tpabort(0); return 1; }
        if (h_amt <= 0) { ctx.skipped++; continue; }   /* 금액 이상 건은 건너뜀 */
        EXEC SQL UPDATE au_authorization SET status = 'S', updated_at = now()
            WHERE auth_id = :h_auth AND status = 'A';
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE cssb; tpabort(0); return 1; }
        ctx.settled++;
        ctx.settled_gross += h_amt;
    }
    EXEC SQL CLOSE cssb;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> au_standin_settle_batch COMMIT: bizdate=%s 정산반영=%ld건 %ld원 skip=%ld any=%d\n",
           ctx.biz_date, ctx.settled, ctx.settled_gross, ctx.skipped, aub_standin_any(&ctx));

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