/*
 * ac_purchase_rankpid_dbio.pgc - ac 모듈 DB 접근 함수 세트 (ac_purchase_rankpid_dbio), archived into libacdbio.a.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 * Shape: rank() OVER (ORDER BY amount DESC) 커서 스캔 후 대상 pid 의 순위 반환.
 */
#include <string.h>
#include <userlog.h>
#include "ac_purchase_rankpid_dbio.h"

/* 금액 순위표에서 지정 매입(pid)의 rank 를 찾아 반환. 미발견 시 0. */
long acdb_purchase_rank_of(const char *bizdate, long pid)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_rk, h_pid, h_amt, target = pid, found = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL DECLARE rkc CURSOR FOR
        SELECT rank() OVER (ORDER BY amount DESC) AS rk, purchase_id, amount
        FROM purchase WHERE biz_date = :h_bizdate;
    EXEC SQL OPEN rkc;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH rkc INTO :h_rk, :h_pid, :h_amt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE rkc; return -1; }
        if (h_pid == target) { found = h_rk; break; }
    }
    EXEC SQL CLOSE rkc;
    return found;
}
