/*
 * mg_rankamt_dbio.pgc - mg 모듈 DB 접근 함수 (mg_rankamt_dbio), archived into libmgdbio.a.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 * 채널별 최고금액(랭크1) 전문 수 (ROW_NUMBER 윈도우 커서).
 */
#include <string.h>
#include <userlog.h>
#include "mg_rankamt_dbio.h"

long mgdb_rank_by_amount(const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_mid, h_rn, 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 mrk CURSOR FOR
        SELECT msg_id,
               ROW_NUMBER() OVER (PARTITION BY channel ORDER BY amount DESC)
        FROM mg_msg_log WHERE biz_date = :h_bizdate;
    EXEC SQL OPEN mrk;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH mrk INTO :h_mid, :h_rn;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE mrk; return -1; }
        if (h_rn == 1) tops++;
    }
    EXEC SQL CLOSE mrk;
    return tops;
}
