/*
 * mm_feerate_dbio.pgc - 수수료율 마스터 upsert + 이력 적재 (libmmdbio.a).
 * ECPG functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 */
#include <string.h>
#include <userlog.h>
#include "mm_dbio.h"

int mmdb_set_fee_rate(const char *merch, const char *card_type, long rate_bps)
{
    EXEC SQL BEGIN DECLARE SECTION;
    long h_id, h_bps = rate_bps;
    char h_merch[64], h_ctype[16];
    EXEC SQL END DECLARE SECTION;

    strncpy(h_merch, merch,     sizeof(h_merch) - 1); h_merch[sizeof(h_merch)-1] = 0;
    strncpy(h_ctype, card_type, sizeof(h_ctype) - 1); h_ctype[sizeof(h_ctype)-1] = 0;

    EXEC SQL INSERT INTO mm_fee_rate (merchant_id, card_type, rate_bps, eff_date)
        VALUES (:h_merch, :h_ctype, :h_bps, current_date)
        ON CONFLICT (merchant_id, card_type) DO UPDATE
        SET rate_bps = EXCLUDED.rate_bps, eff_date = current_date, updated_at = now();
    if (sqlca.sqlcode < 0) {
        userlog("mmdb_set_fee_rate FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc);
        return -1;
    }

    /* 이력 적재 */
    EXEC SQL SELECT nextval('mm_feerate_hist_seq') INTO :h_id;
    if (sqlca.sqlcode < 0) return -1;
    EXEC SQL INSERT INTO mm_fee_rate_hist
        (hist_id, merchant_id, card_type, rate_bps, eff_date)
        VALUES (:h_id, :h_merch, :h_ctype, :h_bps, current_date);
    if (sqlca.sqlcode < 0) {
        userlog("mmdb_set_fee_rate hist FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc);
        return -1;
    }
    return 0;
}

int mmdb_get_fee_rate(const char *merch, const char *card_type, long *bps_out)
{
    EXEC SQL BEGIN DECLARE SECTION;
    long h_bps;
    char h_merch[64], h_ctype[16];
    EXEC SQL END DECLARE SECTION;

    strncpy(h_merch, merch,     sizeof(h_merch) - 1); h_merch[sizeof(h_merch)-1] = 0;
    strncpy(h_ctype, card_type, sizeof(h_ctype) - 1); h_ctype[sizeof(h_ctype)-1] = 0;

    EXEC SQL SELECT rate_bps INTO :h_bps FROM mm_fee_rate
        WHERE merchant_id = :h_merch AND card_type = :h_ctype;
    if (sqlca.sqlcode < 0 || sqlca.sqlcode == 100) {
        userlog("mmdb_get_fee_rate FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc);
        return -1;
    }
    *bps_out = h_bps;
    return 0;
}

long mmdb_feerate_hist_count(const char *merch)
{
    EXEC SQL BEGIN DECLARE SECTION;
    long h_cnt;
    char h_merch[64];
    EXEC SQL END DECLARE SECTION;

    strncpy(h_merch, merch, sizeof(h_merch) - 1); h_merch[sizeof(h_merch)-1] = 0;

    EXEC SQL SELECT count(*) INTO :h_cnt FROM mm_fee_rate_hist
        WHERE merchant_id = :h_merch;
    if (sqlca.sqlcode < 0) {
        userlog("mmdb_feerate_hist_count FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc);
        return -1;
    }
    return h_cnt;
}
