/*
 * lg_agedpend_batch.pgc - lg 미결전표 에이징 배치 (XA).
 *
 * 기준일 대비 미결(D) 전표의 경과일을 4버킷(<=1 / <=7 / <=30 / 30+)으로
 * 나눠 히스토그램을 만들고, 미결 전표에 걸린 차변 금액 합계도 산출한다.
 * 단일 CASE 집계 SQL 1방 + 금액 조인 1방. ONE global XA transaction.
 * Usage: lg_agedpend_batch [AS-OF-DATE]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "lg_dbio.h"
#include "lg_agedpend_batch.h"

int main(int argc, char **argv)
{
    lg_agedpend_rec_t rec;

    EXEC SQL BEGIN DECLARE SECTION;
    char h_asof[16];
    long h_b1, h_b7, h_b30, h_bold, h_amt;
    EXEC SQL END DECLARE SECTION;

    memset(&rec, 0, sizeof(rec));
    strncpy(rec.as_of, (argc > 1) ? argv[1] : "2026-07-19", sizeof(rec.as_of)-1);
    strncpy(h_asof, rec.as_of, sizeof(h_asof)-1); h_asof[sizeof(h_asof)-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(60, 0) < 0) { fprintf(stderr, "tpbegin FAIL: %s\n", tpstrerror(tperrno)); return 1; }

    EXEC SQL SELECT
            coalesce(sum(CASE WHEN CAST(:h_asof AS date) - biz_date <= 1 THEN 1 ELSE 0 END), 0),
            coalesce(sum(CASE WHEN CAST(:h_asof AS date) - biz_date BETWEEN 2 AND 7 THEN 1 ELSE 0 END), 0),
            coalesce(sum(CASE WHEN CAST(:h_asof AS date) - biz_date BETWEEN 8 AND 30 THEN 1 ELSE 0 END), 0),
            coalesce(sum(CASE WHEN CAST(:h_asof AS date) - biz_date > 30 THEN 1 ELSE 0 END), 0)
        INTO :h_b1, :h_b7, :h_b30, :h_bold
        FROM lg_voucher WHERE status = 'D';
    if (sqlca.sqlcode < 0) { fprintf(stderr, "AGE FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    EXEC SQL SELECT coalesce(sum(l.amount), 0) INTO :h_amt
        FROM lg_ledger_line l JOIN lg_voucher v ON v.voucher_id = l.voucher_id
        WHERE v.status = 'D' AND l.dc = 'D';
    if (sqlca.sqlcode < 0) { fprintf(stderr, "AMT FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }

    rec.bucket_1d = h_b1; rec.bucket_7d = h_b7;
    rec.bucket_30d = h_b30; rec.bucket_old = h_bold;
    rec.amount_total = h_amt;
    printf("--- 미결 에이징 (기준 %s) ---\n", rec.as_of);
    printf("    ~1일 %ld | ~7일 %ld | ~30일 %ld | 30일+ %ld\n",
           rec.bucket_1d, rec.bucket_7d, rec.bucket_30d, rec.bucket_old);
    printf(">>> lg_agedpend_batch COMMIT: 미결 %ld건 차변누계 %ld\n",
           rec.bucket_1d + rec.bucket_7d + rec.bucket_30d + rec.bucket_old, rec.amount_total);

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