/*
 * rc_ageing_batch.pgc - 미대사 에이징 배치 (XA).
 * 미해결 예외를 당일/최근7일/7일초과 세 버킷으로 집계해 리포트를 찍고,
 * 7일 초과 장기 미대사가 존재하면 WARN 에이징 경보를 남긴다.
 * 사용법: rc_ageing_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "rc_dbio.h"
#include "rc_ageing_batch.h"

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

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_msg[96];
    long h_b0, h_b7, h_bx;
    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(*) INTO :h_b0 FROM rc_exception
        WHERE resolved = false AND biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) { tpabort(0); return 1; }
    EXEC SQL SELECT count(*) INTO :h_b7 FROM rc_exception
        WHERE resolved = false AND biz_date < CAST(:h_bizdate AS date)
          AND biz_date >= CAST(:h_bizdate AS date) - 7;
    if (sqlca.sqlcode < 0) { tpabort(0); return 1; }
    EXEC SQL SELECT count(*) INTO :h_bx FROM rc_exception
        WHERE resolved = false AND biz_date < CAST(:h_bizdate AS date) - 7;
    if (sqlca.sqlcode < 0) { tpabort(0); return 1; }
    rec.today = h_b0; rec.week = h_b7; rec.over = h_bx;

    if (rec.over > 0) {
        snprintf(h_msg, sizeof(h_msg), "ageing over 7d unresolved: %ld", rec.over);
        EXEC SQL INSERT INTO rc_alert (alert_id, purchase_id, lvl, message, biz_date)
            VALUES (nextval('rc_alert_seq'), 0, 'WARN', :h_msg, :h_bizdate);
        if (sqlca.sqlcode < 0) { tpabort(0); return 1; }
    }

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> %s COMMIT: bizdate=%s today=%ld week=%ld over=%ld\n",
           RC_AGEING_TAG, bizdate, rec.today, rec.week, rec.over);

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