/*
 * vl_rank_dbio.pgc - vl 모듈 DB 접근 함수 (vl_rank_dbio), archived into libvldbio.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 "vl_rank_dbio.h"

long vldb_rank_suspects(const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_sid, h_rn, firsts = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL DECLARE vrk CURSOR FOR
        SELECT suspect_id,
               ROW_NUMBER() OVER (PARTITION BY severity ORDER BY suspect_id)
        FROM vl_suspect WHERE biz_date = :h_bizdate;
    EXEC SQL OPEN vrk;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH vrk INTO :h_sid, :h_rn;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE vrk; return -1; }
        if (h_rn == 1) firsts++;
    }
    EXEC SQL CLOSE vrk;
    return firsts;
}
