/*
 * mm_wavg_limit_dbio.pgc - mm 모듈 DB 접근 함수 (mm_wavg_limit_dbio), archived into libmmdbio.a.
 * 한도 가중 수수료율 평균 (weighted average + JOIN).
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 */
#include <string.h>
#include <userlog.h>
#include "mm_wavg_limit_dbio.h"

/* 일한도로 가중한 CREDIT 수수료율 평균 = sum(rate*limit)/sum(limit). */
long mmdb_wavg_rate(void)
{
    EXEC SQL BEGIN DECLARE SECTION;
    long h_num = 0, h_den = 0;
    EXEC SQL END DECLARE SECTION;
    EXEC SQL SELECT coalesce(sum(f.rate_bps * l.daily_limit),0), coalesce(sum(l.daily_limit),0)
        INTO :h_num, :h_den
        FROM mm_fee_rate f JOIN mm_limit l ON f.merchant_id = l.merchant_id
        WHERE f.card_type = 'CREDIT';
    if (sqlca.sqlcode < 0) return -1;
    if (h_den <= 0) return 0;
    return h_num / h_den;
}
