/*
 * lg_merch_accum_dbio.pgc - lg 모듈 DB 접근 함수 (lg_merch_accum_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_merch_accum_dbio.h"

/* 누적 upsert: 가맹점 잔액에 차/대 증분을 더하고 balance 재계산. */
int lgqdb_merch_accumulate(const char *merch, const char *bizdate, long debit, long credit)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_merch[64], h_bizdate[16];
    long h_dr = debit, h_cr = credit;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_merch, merch, sizeof(h_merch)-1); h_merch[sizeof(h_merch)-1] = 0;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL INSERT INTO lg_merch_bal (merchant_id, biz_date, debit_total, credit_total, balance)
        VALUES (:h_merch, :h_bizdate, :h_dr, :h_cr, :h_dr - :h_cr)
        ON CONFLICT (merchant_id, biz_date) DO UPDATE
        SET debit_total = lg_merch_bal.debit_total + EXCLUDED.debit_total,
            credit_total = lg_merch_bal.credit_total + EXCLUDED.credit_total,
            balance = lg_merch_bal.debit_total + EXCLUDED.debit_total
                    - lg_merch_bal.credit_total - EXCLUDED.credit_total,
            updated_at = now();
    if (sqlca.sqlcode < 0) { userlog("lgqdb_merch_accumulate FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); return -1; }
    return 0;
}
