/*
 * mm_fee_rank_dbio.pgc - mm 모듈 DB 접근 함수 (mm_fee_rank_dbio), archived into libmmdbio.a.
 * 카드유형 내 수수료율 순위 n번째 가맹점 (window RANK).
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 */
#include <string.h>
#include <userlog.h>
#include "mm_fee_rank_dbio.h"

/* card_type 파티션에서 rate_bps 내림차순 rank 번째 가맹점. */
int mmdb_fee_rank(const char *card_type, long rank, char *merch_out)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_ct[16], h_merch[64];
    long h_rank = rank;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_ct, card_type, sizeof(h_ct)-1); h_ct[sizeof(h_ct)-1] = 0;
    EXEC SQL SELECT merchant_id INTO :h_merch FROM (
        SELECT merchant_id, rank() OVER (PARTITION BY card_type ORDER BY rate_bps DESC) AS rk
        FROM mm_fee_rate WHERE card_type = :h_ct) t
        WHERE t.rk = :h_rank LIMIT 1;
    if (sqlca.sqlcode == 100) { merch_out[0] = 0; return 0; }
    if (sqlca.sqlcode < 0) return -1;
    strcpy(merch_out, h_merch);
    return 0;
}
