/*
 * st_feewindow_dbio.pgc - 가맹점별 수수료 상위 라인 (st_feewindow_dbio), libstdbio.a.
 * ECPG; 호출자 XA 브랜치에서 수행, EXEC SQL CONNECT 없음.
 * dense_rank() OVER (PARTITION BY merchant_id ORDER BY amount DESC) 로 가맹점별 상위 3 라인 수.
 */
#include <string.h>
#include <userlog.h>
#include "st_feewindow_dbio.h"

long stdb_top3_fee_lines(const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_mid[32];
    long h_dr, h_amt, tops = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL DECLARE fwc CURSOR FOR
        SELECT merchant_id, amount,
               dense_rank() OVER (PARTITION BY merchant_id ORDER BY amount DESC)
        FROM st_settle_dtl WHERE biz_date = :h_bizdate;
    EXEC SQL OPEN fwc;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH fwc INTO :h_mid, :h_amt, :h_dr;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE fwc; return -1; }
        if (h_dr <= 3) tops++;
    }
    EXEC SQL CLOSE fwc;
    return tops;
}
