/*
 * py_statmonth_batch.pgc - py 월별 지급 집계 리포트 배치 (커서 GROUP BY, XA).
 *
 * 지정 기간의 지급건을 'YYYY-MM' 월 단위로 묶어 월별 건수/net 합을 커서로
 * 훑어 stdout 리포트로 출력한다 (갱신 없음, 읽기 전용 리포트).
 * Usage: py_statmonth_batch [FROM-YYYY-MM-DD] [TO-YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>

int main(int argc, char **argv)
{
    const char *from = (argc > 1) ? argv[1] : "2026-01-01";
    const char *to   = (argc > 2) ? argv[2] : "2026-12-31";
    long months = 0, grand = 0;

    EXEC SQL BEGIN DECLARE SECTION;
    char h_from[16], h_to[16], h_mon[16];
    long h_cnt, h_amt;
    EXEC SQL END DECLARE SECTION;

    strncpy(h_from, from, sizeof(h_from)-1); h_from[sizeof(h_from)-1] = 0;
    strncpy(h_to, to, sizeof(h_to)-1);       h_to[sizeof(h_to)-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(90, 0) < 0) { fprintf(stderr, "tpbegin FAIL: %s\n", tpstrerror(tperrno)); return 1; }

    EXEC SQL DECLARE psm CURSOR FOR
        SELECT to_char(biz_date, 'YYYY-MM'), count(*), coalesce(sum(net),0)
          FROM py_payout WHERE biz_date BETWEEN :h_from AND :h_to
         GROUP BY 1 ORDER BY 1;
    EXEC SQL OPEN psm;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH psm INTO :h_mon, :h_cnt, :h_amt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE psm; tpabort(0); return 1; }
        months++; grand += h_amt;
        printf("  %s: %ld건 %ld원\n", h_mon, h_cnt, h_amt);
    }
    EXEC SQL CLOSE psm;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> py_statmonth_batch COMMIT: months=%ld grand=%ld\n", months, grand);
    tpclose(); tpterm();
    return 0;
}
