/*
 * mg_mtimix_batch.pgc - mg 전문유형(MTI) 구성비 산출 배치 (커서 + XA).
 *
 * MTI 별로 당일 전문을 묶어 유형 가짓수와 금융전문(02xx/04xx) 대
 * 망관리전문(08xx) 비중을 가른다 (전문유형 세분 통계의 일배치판).
 * Usage: mg_mtimix_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "mg_mtimix_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    long pct;
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_mti[8];
    long h_cnt;
    EXEC SQL END DECLARE SECTION;
    mg_mtimix_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 mmx CURSOR FOR
        SELECT mti, count(*) FROM mg_msg_log
        WHERE biz_date = :h_bizdate
        GROUP BY mti ORDER BY mti;
    EXEC SQL OPEN mmx;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH mmx INTO :h_mti, :h_cnt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE mmx; tpabort(0); return 1; }
        rec.kinds++;
        rec.total += h_cnt;
        if (h_mti[1] == '8') rec.net_cnt += h_cnt;   /* 08xx = 망관리 */
        else                 rec.fin_cnt += h_cnt;   /* 그 외 = 금융/취소/정산 */
        printf("    [MTI %.4s] %ld건\n", h_mti, h_cnt);
    }
    EXEC SQL CLOSE mmx;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    pct = (rec.total > 0) ? (rec.fin_cnt * 100L) / rec.total : 0;
    printf(">>> mg_mtimix_batch COMMIT: bizdate=%s 유형=%ld 총=%ld 금융=%ld(%ld%%) 망관리=%ld\n",
           bizdate, rec.kinds, rec.total, rec.fin_cnt, pct, rec.net_cnt);

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