/*
 * cl_snap_rank_dbio.pgc - cl 모듈 DB 접근 함수 (cl_snap_rank_dbio), archived into libcldbio.a.
 * 마감 스냅샷 gross 순위 n번째 가맹점 (window ROW_NUMBER).
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 */
#include <string.h>
#include <userlog.h>
#include "cl_snap_rank_dbio.h"

/* close_id 스냅샷에서 gross 내림차순 rank 번째 가맹점 반환. */
int clqdb_snap_rank(long cid, long rank, char *merch_out)
{
    EXEC SQL BEGIN DECLARE SECTION;
    long h_cid = cid, h_rank = rank;
    char h_merch[64];
    EXEC SQL END DECLARE SECTION;
    EXEC SQL SELECT merchant_id INTO :h_merch FROM (
        SELECT merchant_id, row_number() OVER (ORDER BY gross_amount DESC) AS rn
        FROM cl_snapshot WHERE close_id = :h_cid) t
        WHERE t.rn = :h_rank;
    if (sqlca.sqlcode == 100) { merch_out[0] = 0; return 0; }
    if (sqlca.sqlcode < 0) return -1;
    strcpy(merch_out, h_merch);
    return 0;
}
