/*
 * ac_purchase_topn_dbio.pgc - ac 모듈 DB 접근 함수 세트 (ac_purchase_topn_dbio), archived into libacdbio.a.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 * Shape: window row_number() OVER (ORDER BY amount DESC) 상위 N 매입 금액 누적.
 */
#include <string.h>
#include <userlog.h>
#include "ac_purchase_topn_dbio.h"

/* 금액 내림차순 상위 topn 매입의 amount 합계를 커서 누적으로 반환. */
long acdb_topn_amount_sum(const char *bizdate, long topn)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_rn, h_amt, acc = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL DECLARE tnc CURSOR FOR
        SELECT row_number() OVER (ORDER BY amount DESC) AS rn, amount
        FROM purchase WHERE biz_date = :h_bizdate;
    EXEC SQL OPEN tnc;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH tnc INTO :h_rn, :h_amt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE tnc; return -1; }
        if (h_rn <= topn) acc += h_amt;
    }
    EXEC SQL CLOSE tnc;
    return acc;
}
