/*
 * mg_routegrp_dbio.pgc - mg 모듈 DB 접근 함수 (mg_routegrp_dbio), archived into libmgdbio.a.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 * 라우팅 매칭 전문의 목적지별 최대 금액그룹 수 (JOIN + GROUP BY 커서).
 */
#include <string.h>
#include <userlog.h>
#include "mg_routegrp_dbio.h"

long mgdb_route_amount_groups(const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_dest[64];
    long h_sum, groups = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL DECLARE mrg CURSOR FOR
        SELECT r.dest, coalesce(sum(m.amount),0)
        FROM mg_msg_log m JOIN mg_route r ON r.channel = m.channel AND r.mti = m.mti
        WHERE m.biz_date = :h_bizdate AND r.active
        GROUP BY r.dest;
    EXEC SQL OPEN mrg;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH mrg INTO :h_dest, :h_sum;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE mrg; return -1; }
        groups++;
    }
    EXEC SQL CLOSE mrg;
    return groups;
}
