/*
 * st_recvage_batch.pgc - 미수금 연령 분석 배치 (XA 배치).
 * 보류(HELD) 지급을 기준일 대비 지급일 경과에 따라 연령 구간(정상/연체)으로 나누어
 * 건수와 금액을 집계, 미수금 노후화 규모를 출력한다 (집계 전용).
 * 사용법: st_recvage_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "st_dbio.h"
#include "st_recvage_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    st_recvage_rec_t rec;
    memset(&rec, 0, sizeof(rec));
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_cnt, h_sum, h_overdue;
    EXEC SQL END DECLARE SECTION;

    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(60, 0) < 0) { fprintf(stderr, "tpbegin FAIL: %s\n", tpstrerror(tperrno)); return 1; }

    EXEC SQL SELECT count(*), coalesce(sum(net_amount),0) INTO :h_cnt, :h_sum
        FROM st_payment WHERE status = 'HELD';
    if (sqlca.sqlcode < 0) { fprintf(stderr, "SUM FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
    rec.held_cnt = h_cnt; rec.recv_total = h_sum;

    EXEC SQL SELECT count(*) INTO :h_overdue FROM st_payment
        WHERE status = 'HELD' AND pay_date < :h_bizdate;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OVERDUE FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
    rec.oldest = h_overdue;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> %s COMMIT: bizdate=%s held_cnt=%ld recv_total=%ld overdue_cnt=%ld\n",
           ST_RECVAGE_TAG, bizdate, rec.held_cnt, rec.recv_total, rec.oldest);
    tpclose(); tpterm();
    return 0;
}
