/*
 * au_limit_query_dbio.pgc - au 모듈 DB 접근 함수 세트 (au_limit_query_dbio), archived into libaudbio.a.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 * Shape: computed column SELECT + guarded division.
 */
#include <string.h>
#include <userlog.h>
#include "au_limit_query_dbio.h"

/* 가용한도 = daily_limit - used_amount (DB 계산). */
long audb_limit_available(const char *card)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_card[24];
    long h_v = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_card, card, sizeof(h_card)-1); h_card[sizeof(h_card)-1] = 0;
    EXEC SQL SELECT coalesce(daily_limit - used_amount, 0) INTO :h_v
        FROM card_limit WHERE card_no = :h_card;
    if (sqlca.sqlcode < 0 || sqlca.sqlcode == 100) return -1;
    return h_v;
}

/* 한도 소진율(%) = used_amount*100/daily_limit (0 나눗셈 방지). */
long audb_limit_utilization(const char *card)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_card[24];
    long h_lim = 0, h_used = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_card, card, sizeof(h_card)-1); h_card[sizeof(h_card)-1] = 0;
    EXEC SQL SELECT coalesce(daily_limit,0), coalesce(used_amount,0)
        INTO :h_lim, :h_used FROM card_limit WHERE card_no = :h_card;
    if (sqlca.sqlcode < 0 || sqlca.sqlcode == 100) return -1;
    if (h_lim <= 0) return 0;
    return h_used * 100 / h_lim;
}
