/*
 * st_payrank_dbio.pgc - st 모듈 DB 접근 함수 세트 (st_payrank_dbio), archived into libstdbio.a.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 * 윈도우(rank) 커서 - 상위 N 지급 net 합계.
 */
#include <string.h>
#include <userlog.h>
#include "st_payrank_dbio.h"

long stdb_top_payment_sum(const char *bizdate, long topn)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_top = topn, h_rnk, h_net, total = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL DECLARE prc CURSOR FOR
        SELECT net_amount, rank() OVER (ORDER BY net_amount DESC) AS rnk
        FROM st_payment WHERE biz_date = :h_bizdate;
    EXEC SQL OPEN prc;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH prc INTO :h_net, :h_rnk;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE prc; return -1; }
        if (h_rnk <= h_top) total += h_net;
    }
    EXEC SQL CLOSE prc;
    return total;
}
