/*
 * ac_merchsum_query_dbio.pgc - ac 모듈 DB 접근 함수 세트 (ac_merchsum_query_dbio), archived into libacdbio.a.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 */
#include <string.h>
#include <userlog.h>
#include "ac_merchsum_query_dbio.h"

/* 최대 gross 를 기록한 가맹점의 gross 반환. */
long acdb_merchsum_peak_gross(const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_v = 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(max(gross_amount),0) INTO :h_v FROM merchant_summary WHERE biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) return -1;
    return h_v;
}

/* 건당 평균 수수료 = sum(fee)/sum(txn_count). */
long acdb_merchsum_avg_fee(const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_fee = 0, h_txn = 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(fee_amount),0), coalesce(sum(txn_count),0)
        INTO :h_fee, :h_txn FROM merchant_summary WHERE biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) return -1;
    if (h_txn <= 0) return 0;
    return h_fee / h_txn;
}
