/*
 * py_payout_window_dbio.pgc - py 모듈 DB 접근 함수 세트 (py_payout_window_dbio), archived into libpydbio.a.
 * 가맹점별 지급 순액을 윈도우 누계로 계산해 최대 누계선을 구한다.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 */
#include <string.h>
#include <userlog.h>
#include "py_payout_window_dbio.h"

/* 윈도우 함수: 가맹점별 payout_id 순 누계(net) 중 최대값. */
long pydb_payout_peak_running(const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_peak = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL SELECT coalesce(max(run_tot),0) INTO :h_peak FROM (
        SELECT sum(net) OVER (PARTITION BY merchant_id ORDER BY payout_id) AS run_tot
        FROM py_payout WHERE biz_date = :h_bizdate) w;
    if (sqlca.sqlcode < 0) { userlog("pydb_payout_peak_running FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); return -1; }
    return h_peak;
}
