/*
 * lg_line_window_dbio.pgc - lg 모듈 DB 접근 함수 (lg_line_window_dbio), archived into liblgdbio.a.
 * 계정 분개를 라인 순서로 누계(차변 +, 대변 -)한 잔액의 최대치를 윈도우로 구한다.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 */
#include <string.h>
#include <userlog.h>
#include "lg_line_window_dbio.h"

/* 윈도우 누계: 계정 분개 진행잔액(차-대) 의 최고점. */
long lgqdb_running_balance_peak(const char *acct, const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_acct[32], h_bizdate[16];
    long h_peak = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_acct, acct, sizeof(h_acct)-1); h_acct[sizeof(h_acct)-1] = 0;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL SELECT coalesce(max(run_bal),0) INTO :h_peak FROM (
        SELECT sum(CASE WHEN dc = 'D' THEN amount ELSE -amount END)
               OVER (ORDER BY line_id) AS run_bal
        FROM lg_ledger_line WHERE acct = :h_acct AND biz_date = :h_bizdate) w;
    if (sqlca.sqlcode < 0) { userlog("lgqdb_running_balance_peak FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); return -1; }
    return h_peak;
}
