/*
 * st_fee_dbio.pgc - 수수료 구간요율 조회 + 정산 조정 DB 접근 (libstdbio.a).
 * ECPG 함수; 호출자의 XA 브랜치에서 수행. EXEC SQL CONNECT 없음.
 */
#include <string.h>
#include <userlog.h>
#include "st_dbio.h"

/* 금액에 해당하는 최상위 구간 요율(bps)을 반환. 없으면 0, SQL 오류면 -1. */
long stdb_lookup_rate(const char *fee_type, long amount)
{
    EXEC SQL BEGIN DECLARE SECTION;
    long h_bps, h_amt = amount;
    char h_type[16];
    EXEC SQL END DECLARE SECTION;

    strncpy(h_type, fee_type, sizeof(h_type) - 1); h_type[sizeof(h_type)-1] = 0;

    EXEC SQL SELECT rate_bps INTO :h_bps FROM st_fee_rate
        WHERE fee_type = :h_type AND band_min <= :h_amt
        ORDER BY band_min DESC LIMIT 1;
    if (sqlca.sqlcode == 100) return 0;
    if (sqlca.sqlcode < 0) {
        userlog("stdb_lookup_rate FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc);
        return -1;
    }
    return h_bps;
}

long stdb_insert_adjust(long sid, long pid, long delta, const char *reason,
                        const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    long h_id, h_sid = sid, h_pid = pid, h_delta = delta;
    char h_reason[128], h_bizdate[16];
    EXEC SQL END DECLARE SECTION;

    strncpy(h_reason, reason, sizeof(h_reason) - 1);   h_reason[sizeof(h_reason)-1] = 0;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate) - 1); h_bizdate[sizeof(h_bizdate)-1] = 0;

    EXEC SQL SELECT nextval('st_adj_seq') INTO :h_id;
    if (sqlca.sqlcode < 0) return -1;

    EXEC SQL INSERT INTO st_adjust (adj_id, settlement_id, purchase_id, delta, reason, biz_date)
        VALUES (:h_id, :h_sid, :h_pid, :h_delta, :h_reason, :h_bizdate);
    if (sqlca.sqlcode < 0) {
        userlog("stdb_insert_adjust FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc);
        return -1;
    }
    return h_id;
}
