/*
 * lg_carry_forward_dbio.pgc - lg 모듈 DB 접근 함수 (lg_carry_forward_dbio), archived into liblgdbio.a.
 * 계정잔액 익일 이월 upsert (insert..select).
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 */
#include <string.h>
#include <userlog.h>
#include "lg_carry_forward_dbio.h"

/* 당일 계정잔액을 익일 개시잔액으로 이월, 이월 계정 수 반환. */
long lgqdb_carry_forward(const char *bizdate, const char *nextday)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_next[16];
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    strncpy(h_next, nextday, sizeof(h_next)-1); h_next[sizeof(h_next)-1] = 0;
    EXEC SQL INSERT INTO lg_account_bal (acct, biz_date, debit_total, credit_total, balance)
        SELECT acct, :h_next, 0, 0, balance FROM lg_account_bal WHERE biz_date = :h_bizdate
        ON CONFLICT (acct, biz_date) DO UPDATE SET balance = EXCLUDED.balance, updated_at = now();
    if (sqlca.sqlcode < 0) { userlog("lgqdb_carry_forward FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); return -1; }
    return sqlca.sqlerrd[2];
}
