/*
 * st_feeweight_dbio.pgc - 금액 가중 평균 요율 (st_feeweight_dbio), libstdbio.a.
 * ECPG; st_settle_dtl 를 st_fee_rate 와 조인해 sum(amount*rate_bps)/nullif(sum(amount),0) 가중평균.
 */
#include <string.h>
#include <userlog.h>
#include "st_feeweight_dbio.h"

long stdb_weighted_rate(const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    double h_w = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL SELECT coalesce(sum(d.amount * r.rate_bps)::float8 / nullif(sum(d.amount), 0), 0)
        INTO :h_w FROM st_settle_dtl d
        JOIN st_fee_rate r ON r.fee_type = d.fee_type AND d.amount >= r.band_min
        WHERE d.biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) { userlog("stdb_weighted_rate FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); return -1; }
    return (long) h_w;
}
