/*
 * lg_trial_load_dbio.pgc - lg 모듈 DB 접근 함수 (lg_trial_load_dbio), archived into liblgdbio.a.
 * 원장 라인을 계정별 차/대 합으로 집계해 시산표에 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_trial_load_dbio.h"

/* INSERT..SELECT: 계정별 차변/대변/차액을 시산표에 upsert 적재, 계정 수 반환. */
long lgqdb_trial_load(const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL INSERT INTO lg_trial_bal (acct, biz_date, debit_total, credit_total, diff)
        SELECT acct, :h_bizdate,
               coalesce(sum(amount) FILTER (WHERE dc = 'D'),0),
               coalesce(sum(amount) FILTER (WHERE dc = 'C'),0),
               coalesce(sum(amount) FILTER (WHERE dc = 'D'),0)
             - coalesce(sum(amount) FILTER (WHERE dc = 'C'),0)
        FROM lg_ledger_line WHERE biz_date = :h_bizdate GROUP BY acct
        ON CONFLICT (acct, biz_date) DO UPDATE
        SET debit_total = EXCLUDED.debit_total, credit_total = EXCLUDED.credit_total,
            diff = EXCLUDED.diff, updated_at = now();
    if (sqlca.sqlcode < 0) { userlog("lgqdb_trial_load FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); return -1; }
    return sqlca.sqlerrd[2];
}
