/*
 * au_cancel_reproc_batch.pgc - au 미반영 승인취소 재처리 배치 (조인 커서 + 분기 UPDATE, XA).
 *
 * 영업일의 취소 접수(au_cancel) 중 원승인이 아직 취소류 상태가 아닌 건을
 * 조인 커서로 골라, 유형별로 분기 반영한다: FULL->C, VOID->V,
 * PARTIAL->원승인 금액 감액(원금액 미만일 때만). 전량 ONE XA transaction.
 * Usage: au_cancel_reproc_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "au_cancel_reproc_batch.h"

long aub_cancel_reproc_total(const au_cancel_reproc_ctx_t *ctx)
{
    return ctx->reproc_full + ctx->reproc_void + ctx->reproc_partial;
}

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

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_ctype[12], h_astat[4];
    long h_auth, h_camt, h_aamt;
    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 ccrb CURSOR FOR
        SELECT c.auth_id, c.cancel_type, c.amount, a.status, a.amount
        FROM au_cancel c JOIN au_authorization a ON a.auth_id = c.auth_id
        WHERE c.biz_date = :h_bizdate AND a.status NOT IN ('C','V','R')
        ORDER BY c.cancel_id;
    EXEC SQL OPEN ccrb;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH ccrb INTO :h_auth, :h_ctype, :h_camt, :h_astat, :h_aamt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE ccrb; tpabort(0); return 1; }

        if (h_astat[0] != 'A' && h_astat[0] != 'M') { ctx.skipped++; continue; }

        if (strcmp(h_ctype, "PARTIAL") == 0) {
            if (h_camt >= h_aamt) { ctx.skipped++; continue; }   /* 정합성 오류 건 스킵 */
            EXEC SQL UPDATE au_authorization
                SET amount = amount - :h_camt, updated_at = now()
                WHERE auth_id = :h_auth;
            if (sqlca.sqlcode < 0) { EXEC SQL CLOSE ccrb; tpabort(0); return 1; }
            ctx.reproc_partial++;
        } else if (strcmp(h_ctype, "VOID") == 0) {
            EXEC SQL UPDATE au_authorization SET status = 'V', updated_at = now()
                WHERE auth_id = :h_auth;
            if (sqlca.sqlcode < 0) { EXEC SQL CLOSE ccrb; tpabort(0); return 1; }
            ctx.reproc_void++;
        } else {
            EXEC SQL UPDATE au_authorization SET status = 'C', updated_at = now()
                WHERE auth_id = :h_auth;
            if (sqlca.sqlcode < 0) { EXEC SQL CLOSE ccrb; tpabort(0); return 1; }
            ctx.reproc_full++;
        }
    }
    EXEC SQL CLOSE ccrb;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> au_cancel_reproc_batch COMMIT: bizdate=%s 재처리=%ld (FULL=%ld VOID=%ld PARTIAL=%ld) skip=%ld\n",
           ctx.biz_date, aub_cancel_reproc_total(&ctx),
           ctx.reproc_full, ctx.reproc_void, ctx.reproc_partial, ctx.skipped);

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