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

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

/* 단일 지급 원장 잔액 = XFER(-) 그 외(+), 커서 부호 누적. */
long pydb_ledger_balance(long payout_id)
{
    EXEC SQL BEGIN DECLARE SECTION;
    long h_pay = payout_id, h_amt, bal = 0;
    char h_type[16];
    EXEC SQL END DECLARE SECTION;
    EXEC SQL DECLARE plbc CURSOR FOR
        SELECT entry_type, amount FROM py_ledger WHERE payout_id = :h_pay;
    EXEC SQL OPEN plbc;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH plbc INTO :h_type, :h_amt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE plbc; return -1; }
        bal += (h_type[0] == 'X') ? -h_amt : h_amt;
    }
    EXEC SQL CLOSE plbc;
    return bal;
}
