/*
 * lg_baddebt_batch.pgc - lg 대손 일괄 처리 배치 (커서 + XA).
 *
 * 기준 경과일(threshold, 기본 90일)을 넘긴 미대사(A) 매입 채권을 가맹점별로
 * 합산해 D:BADDEBT_EXP / C:RECV 균형 전표로 일괄 상각하고 가맹점 잔액을
 * 재산출한다. 모두 ONE global XA transaction 에서 수행.
 * Usage: lg_baddebt_batch [YYYY-MM-DD] [THRESHOLD_DAYS]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "lg_dbio.h"
#include "lg_baddebt_batch.h"

int main(int argc, char **argv)
{
    lg_baddebt_rec_t rec;
    long vid;

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_merch[64];
    long h_days, h_amt;
    EXEC SQL END DECLARE SECTION;

    memset(&rec, 0, sizeof(rec));
    strncpy(rec.biz_date, (argc > 1) ? argv[1] : "2026-07-19", sizeof(rec.biz_date)-1);
    rec.threshold_days = (argc > 2) ? atol(argv[2]) : 90;
    if (rec.threshold_days <= 0) rec.threshold_days = 90;
    strncpy(h_bizdate, rec.biz_date, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    h_days = rec.threshold_days;

    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 DECLARE bd_cur CURSOR FOR
        SELECT merchant_id, coalesce(sum(amount), 0)
        FROM purchase
        WHERE status = 'A' AND CAST(:h_bizdate AS date) - biz_date > :h_days
        GROUP BY merchant_id HAVING sum(amount) > 0
        ORDER BY merchant_id;
    EXEC SQL OPEN bd_cur;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH bd_cur INTO :h_merch, :h_amt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d]\n", sqlca.sqlcode); EXEC SQL CLOSE bd_cur; tpabort(0); return 1; }

        vid = lgdb_next_voucher_id();
        if (vid < 0) { EXEC SQL CLOSE bd_cur; tpabort(0); return 1; }
        if (lgdb_insert_voucher(vid, "ADJ", 0, "P", rec.biz_date, "대손 일괄상각") < 0 ||
            lgdb_insert_line(vid, "BADDEBT_EXP", "D", h_amt, h_merch, rec.biz_date, "posted") < 0 ||
            lgdb_insert_line(vid, "RECV", "C", h_amt, h_merch, rec.biz_date, "posted") < 0 ||
            lgdb_upsert_merch_bal(h_merch, rec.biz_date) < 0)
            { EXEC SQL CLOSE bd_cur; tpabort(0); return 1; }
        printf("    대손: %s %ld (vid=%ld)\n", h_merch, h_amt, vid);
        rec.written_off += h_amt;
        rec.merchants++;
    }
    EXEC SQL CLOSE bd_cur;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> lg_baddebt_batch COMMIT: %ld일 초과 %ld가맹점 대손 %ld 상각 (차=대 균형)\n",
           rec.threshold_days, rec.merchants, rec.written_off);

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