/*
 * ac_ledger_query_dbio.pgc - ac 모듈 DB 접근 함수 세트 (ac_ledger_query_dbio), archived into libacdbio.a.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 */
#include <string.h>
#include <userlog.h>
#include "ac_ledger_query_dbio.h"

/* RECON/SETTLE 엔트리를 한 번에 분리 집계하고 SETTLE 합 반환. */
long acdb_ledger_settle_sum(const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_recon = 0, h_settle = 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(sum(amount) FILTER (WHERE entry_type = 'RECON'), 0),
        coalesce(sum(amount) FILTER (WHERE entry_type = 'SETTLE'), 0)
        INTO :h_recon, :h_settle FROM ledger WHERE biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) return -1;
    if (h_recon < 0) return -1;
    return h_settle;
}

/* 단일 매입 원장 잔액 = SETTLE(+) - XFER(-), 커서 부호 누적. */
long acdb_ledger_balance(long pid)
{
    EXEC SQL BEGIN DECLARE SECTION;
    long h_pid, h_amt, bal = 0;
    char h_type[16];
    EXEC SQL END DECLARE SECTION;
    h_pid = pid;
    EXEC SQL DECLARE lbc CURSOR FOR
        SELECT entry_type, amount FROM ledger WHERE purchase_id = :h_pid;
    EXEC SQL OPEN lbc;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH lbc INTO :h_type, :h_amt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE lbc; return -1; }
        bal += (h_type[0] == 'X') ? -h_amt : h_amt;
    }
    EXEC SQL CLOSE lbc;
    return bal;
}
