/*
 * au_auth_rankcard_dbio.pgc - au 모듈 DB 접근 함수 세트 (au_auth_rankcard_dbio), archived into libaudbio.a.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 * Shape: rank() OVER (ORDER BY amount DESC) 커서에서 목표 순위의 금액 반환.
 */
#include <string.h>
#include <userlog.h>
#include "au_auth_rankcard_dbio.h"

/* 금액 순위표에서 target_rank 위에 해당하는 승인 금액을 반환. 없으면 0. */
long audb_auth_amount_at_rank(const char *bizdate, long target_rank)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_rk, h_aid, h_amt, tr = target_rank, hit = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL DECLARE arc CURSOR FOR
        SELECT rank() OVER (ORDER BY amount DESC) AS rk, auth_id, amount
        FROM au_authorization WHERE biz_date = :h_bizdate AND status = 'A';
    EXEC SQL OPEN arc;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH arc INTO :h_rk, :h_aid, :h_amt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE arc; return -1; }
        if (h_rk == tr) { hit = h_amt; break; }
    }
    EXEC SQL CLOSE arc;
    return hit;
}
