/*
 * py_failstat_batch.pgc - py 지급 실패사유 집계 리포트 배치 (GROUP BY 커서, XA).
 *
 * 당일 반려(J)건을 사유별 커서로 집계해 사유/건수/금액 표를 출력하고
 * 최다 사유를 강조 리포트한다 (read-only 분석 배치).
 * host 변수는 전용 카피북 py_failstat_cpy.h 를 EXEC SQL INCLUDE.
 * Usage: py_failstat_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    long groups = 0, fails = 0, amount = 0;
    char top_reason[128] = "";
    long top_cnt = 0;

    EXEC SQL INCLUDE py_failstat_cpy;

    strncpy(c_bizdate, bizdate, sizeof(c_bizdate)-1); c_bizdate[sizeof(c_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 pfs CURSOR FOR
        SELECT coalesce(nullif(reject_reason,''),'(사유미기재)'), count(*), coalesce(sum(net),0)
          FROM py_payout
         WHERE biz_date = :c_bizdate AND status = 'J'
         GROUP BY 1 ORDER BY 2 DESC, 1;
    EXEC SQL OPEN pfs;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH pfs INTO :c_reason, :c_cnt, :c_amt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE pfs; tpabort(0); return 1; }
        printf("  [실패사유] %-24s %6ld건 %12ld원\n", c_reason, c_cnt, c_amt);
        if (groups == 0) { strncpy(top_reason, c_reason, sizeof(top_reason)-1); top_cnt = c_cnt; }
        groups++; fails += c_cnt; amount += c_amt;
    }
    EXEC SQL CLOSE pfs;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    if (groups > 0)
        printf(">>> py_failstat_batch COMMIT: bizdate=%s 사유=%ld종 반려=%ld건/%ld원 최다='%s'(%ld건)\n",
               bizdate, groups, fails, amount, top_reason, top_cnt);
    else
        printf(">>> py_failstat_batch COMMIT: bizdate=%s 반려 없음\n", bizdate);

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