/*
 * mg_rcdist_batch.pgc - mg 응답코드 분포 리포트 배치 (커서 + XA).
 *
 * rc 별 GROUP BY 커서로 당일 정상(00)/거절 분포와 최빈 거절코드를 뽑아
 * 거절 코드 급증을 조기에 드러낸다 (응답코드 세분 통계의 일배치판).
 * Usage: mg_rcdist_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "mg_rcdist_batch.h"

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

    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 rdb CURSOR FOR
        SELECT rc, count(*) FROM mg_msg_log
        WHERE biz_date = :h_bizdate
        GROUP BY rc ORDER BY count(*) DESC, rc;
    EXEC SQL OPEN rdb;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH rdb INTO :h_rc, :h_cnt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE rdb; tpabort(0); return 1; }
        rec.kinds++;
        if (h_rc[0] == '0' && h_rc[1] == '0') {
            rec.ok_cnt += h_cnt;
        } else {
            rec.bad_cnt += h_cnt;
            if (h_cnt > top_cnt) { top_cnt = h_cnt; strncpy(rec.top_rc, h_rc, 3); rec.top_rc[3] = 0; }
        }
        printf("    [rc %.2s] %ld건\n", h_rc, h_cnt);
    }
    EXEC SQL CLOSE rdb;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mg_rcdist_batch COMMIT: bizdate=%s 코드=%ld종 정상=%ld 거절=%ld 최빈거절=%s\n",
           bizdate, rec.kinds, rec.ok_cnt, rec.bad_cnt, rec.top_rc[0] ? rec.top_rc : "-");

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