/*
 * rc_alertwin_dbio.pgc - rc 모듈 DB 접근 함수 세트 (rc_alertwin_dbio), archived into librcdbio.a.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 * 윈도우 함수(row_number) 커서 - 최근 N 경보 내 WARN 수.
 */
#include <string.h>
#include <userlog.h>
#include "rc_alertwin_dbio.h"

long rcdb_recent_warn_count(const char *bizdate, long topn)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_lvl[16];
    long h_top = topn, h_rn, warns = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL DECLARE awc CURSOR FOR
        SELECT lvl, row_number() OVER (ORDER BY alert_id DESC) AS rn
        FROM rc_alert WHERE biz_date = :h_bizdate;
    EXEC SQL OPEN awc;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH awc INTO :h_lvl, :h_rn;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE awc; return -1; }
        if (h_rn <= h_top && strcmp(h_lvl, "WARN") == 0) warns++;
    }
    EXEC SQL CLOSE awc;
    return warns;
}
