/*
 * ac_cbaging_batch.pgc - ac 지불거절 경과일 aging 배치 (버킷 집계, XA).
 *
 * ATMI client: 한 글로벌 트랜잭션 안에서 CB 접수 건을 등록 경과일 기준
 * 3개 버킷(7일 미만/7~30일/30일 초과)으로 나눠 세고, 방어되지 않은 장기
 * 미제 건수를 함께 보고한다. tpcommit 이 XA 2PC 를 마무리한다.
 * Usage: ac_cbaging_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "ac_cbaging_batch.h"

/* 경과일을 aging 버킷 인덱스로 변환 */
int acb_cb_bucket(long age_days)
{
    if (age_days < 7) return 0;
    if (age_days <= 30) return 1;
    return 2;
}

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

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_fresh = 0, h_mid = 0, h_stale = 0, h_open = 0;
    EXEC SQL END DECLARE SECTION;

    memset(&cx, 0, sizeof(cx));
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    strncpy(cx.base_date, bizdate, sizeof(cx.base_date)-1);

    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 SELECT
        count(*) FILTER (WHERE CAST(:h_bizdate AS date) - biz_date < 7),
        count(*) FILTER (WHERE CAST(:h_bizdate AS date) - biz_date BETWEEN 7 AND 30),
        count(*) FILTER (WHERE CAST(:h_bizdate AS date) - biz_date > 30),
        count(*) FILTER (WHERE reason NOT LIKE 'DEFEND:%')
        INTO :h_fresh, :h_mid, :h_stale, :h_open
        FROM ac_cancel WHERE cancel_type = 'CB';
    if (sqlca.sqlcode < 0) { fprintf(stderr, "ac_cbaging_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    cx.fresh = h_fresh; cx.mid = h_mid; cx.stale = h_stale; cx.undefended = h_open;
    (void)acb_cb_bucket(31);

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> ac_cbaging_batch COMMIT: base=%s fresh=%ld mid=%ld stale=%ld undefended=%ld\n",
           cx.base_date, cx.fresh, cx.mid, cx.stale, cx.undefended);

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