/* @tier medium @module mg @transform msg-gateway-online */
/*
 * mg_ol_0032.pgc - 전문게이트웨이 전문 라우팅 통계 조회 서비스 (MG_OL_0032)  [tier=medium]
 *
 * 지정 영업일(BIZDATE)의 처리원장(mg_ledger)을 채널코드(chan_cd)별로 집계
 * (count GROUP BY)하여 채널 수·총 전문건수·최다 처리채널(상위채널)을 산출한다.
 * 커서로 집계결과를 순회하며 최상위 채널을 선별해 응답한다.
 * (ATMI void SVC(TPSVCINFO*) 대응)
 */
#include <stdio.h>
#include <string.h>

#include "txcore.h"
#include "txcore_dbio.h"
#include "acq_util.h"
#include "mg_core.h"

EXEC SQL INCLUDE sqlca;

TX_SERVICE(MG_OL_0032, ctx)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_biz_date[9];
    char h_chan_cd[9];
    long h_chan_cnt;
    EXEC SQL END DECLARE SECTION;

    char bizdate[16];
    char top_chan[9];
    long top_cnt = 0, total_cnt = 0, chan_num = 0;

    tx_log(TX_LOG_INFO, "[MG_OL_0032] 전문 라우팅 통계 조회 서비스 진입");

    /* 1) 집계 대상 영업일 수신/검증 */
    if (tx_buf_get(ctx->in, "BIZDATE", bizdate, sizeof(bizdate)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[MG_OL_0032] BIZDATE 누락");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }
    if (!date_is_valid(bizdate)) {
        tx_log(TX_LOG_WARN, "[MG_OL_0032] 영업일 형식 오류 date=%s", bizdate);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESP", RESP_INVALID);
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    strncpy(h_biz_date, bizdate, sizeof(h_biz_date) - 1);
    h_biz_date[sizeof(h_biz_date) - 1] = '\0';
    memset(top_chan, 0, sizeof(top_chan));

    /* 2) 채널별 전문건수 집계 커서 (건수 내림차순) */
    EXEC SQL DECLARE cur_mg_ol_0032 CURSOR FOR
        SELECT chan_cd, count(*)
          FROM mg_ledger
         WHERE biz_date = :h_biz_date
         GROUP BY chan_cd
         ORDER BY count(*) DESC;

    EXEC SQL OPEN cur_mg_ol_0032;
    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("OPEN cur_mg_ol_0032");
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESP", RESP_SYSERR);
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }

    /* 3) 집계결과 순회: 총건수 누적 + 최상위 채널 선별 */
    for (;;) {
        EXEC SQL FETCH cur_mg_ol_0032 INTO :h_chan_cd, :h_chan_cnt;
        if (sqlca.sqlcode == TX_SQL_NOTFOUND)
            break;
        if (sqlca.sqlcode != TX_SQL_OK) {
            TX_DBIO_LOG_ERR("FETCH cur_mg_ol_0032");
            EXEC SQL CLOSE cur_mg_ol_0032;
            tx_buf_reset(ctx->out);
            tx_buf_sets(ctx->out, "RESP", RESP_SYSERR);
            tx_return(ctx, TX_EDB, ctx->out);
            return;
        }

        total_cnt += h_chan_cnt;
        chan_num++;
        if (h_chan_cnt > top_cnt) {
            top_cnt = h_chan_cnt;
            strncpy(top_chan, h_chan_cd, sizeof(top_chan) - 1);
            top_chan[sizeof(top_chan) - 1] = '\0';
        }
    }

    EXEC SQL CLOSE cur_mg_ol_0032;

    /* 4) 집계대상 없음 처리 */
    if (chan_num == 0) {
        tx_log(TX_LOG_INFO, "[MG_OL_0032] 집계대상 없음 date=%s", bizdate);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESP", RESP_OK);
        tx_buf_sets(ctx->out, "BIZDATE", bizdate);
        tx_buf_setlong(ctx->out, "CHANNUM", 0);
        tx_buf_setlong(ctx->out, "TOTALCNT", 0);
        tx_return(ctx, TX_OK, ctx->out);
        return;
    }

    /* 5) 통계결과 응답 (상위채널 포함) */
    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "RESP", RESP_OK);
    tx_buf_sets(ctx->out, "BIZDATE", bizdate);
    tx_buf_setlong(ctx->out, "CHANNUM", chan_num);
    tx_buf_setlong(ctx->out, "TOTALCNT", total_cnt);
    tx_buf_sets(ctx->out, "TOPCHAN", top_chan);
    tx_buf_setlong(ctx->out, "TOPCNT", top_cnt);
    tx_log(TX_LOG_INFO, "[MG_OL_0032] 통계완료 date=%s 채널수=%ld 총건수=%ld 상위채널=%s(%ld)",
           bizdate, chan_num, total_cnt, top_chan, top_cnt);
    tx_return(ctx, TX_OK, ctx->out);
}
