/*
 * ac_fx_weightavg_dbio.pgc - ac 모듈 DB 접근 함수 세트 (ac_fx_weightavg_dbio), archived into libacdbio.a.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 * Shape: KRW 금액 가중 평균 환율 = sum(rate_bps*krw_amount)/sum(krw_amount).
 */
#include <string.h>
#include <userlog.h>
#include "ac_fx_weightavg_dbio.h"

/* 원화 환산액을 가중치로 하는 평균 환율(bps). 가중치 0 이면 0 반환. */
long acdb_fx_weighted_rate(const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_num = 0, h_den = 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(rate_bps * krw_amount), 0),
        coalesce(sum(krw_amount), 0)
        INTO :h_num, :h_den FROM ac_fx WHERE biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) return -1;
    if (h_den <= 0) return 0;
    return h_num / h_den;
}
