/*
 * rc_holdrsn_batch.pgc - 대사 보류 사유별 집계 배치 (커서 + XA).
 * 당일 미해결 예외를 사유별 GROUP BY 커서로 순회하며 사유마다 건수 리포트를
 * 찍고 rc_diff 에 CNT 유형 사유별 건수 라인을 적재한다 (많은 순 정렬).
 * 사용법: rc_holdrsn_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "rc_dbio.h"
#include "rc_holdrsn_batch.h"

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

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_reason[64];
    long h_cnt;
    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 DECLARE chb CURSOR FOR
        SELECT reason, count(*) FROM rc_exception
        WHERE biz_date = :h_bizdate AND resolved = false
        GROUP BY reason ORDER BY count(*) DESC, reason;
    EXEC SQL OPEN chb;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH chb INTO :h_reason, :h_cnt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE chb; tpabort(0); return 1; }
        strncpy(rec.reason, h_reason, sizeof(rec.reason)-1); rec.reason[sizeof(rec.reason)-1] = 0;
        rec.cnt = h_cnt;
        printf("    reason=%-32s cnt=%ld\n", rec.reason, rec.cnt);
        EXEC SQL INSERT INTO rc_diff
            (diff_id, purchase_id, expected_amt, actual_amt, diff_amt, diff_kind, biz_date)
            VALUES (nextval('rc_diff_seq'), 0, 0, :h_cnt, :h_cnt, 'CNT', :h_bizdate);
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE chb; tpabort(0); return 1; }
        reasons++;
    }
    EXEC SQL CLOSE chb;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> %s COMMIT: bizdate=%s reasons=%ld\n", RC_HOLDRSN_TAG, bizdate, reasons);

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