/* @tier easy @module lg @transform ledger-dbio */
/*
 * lg_io_0019.pgc - 원장 보조 DBIO (ECPG)  [tier=easy]
 */
#include <stdio.h>
#include <string.h>

#include "txcore.h"
#include "txcore_dbio.h"
#include "lg_io_0019.h"

EXEC SQL INCLUDE sqlca;

int lg_io_0019_fetch(const char *key, long *out_amount)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_key[32];
    long h_val;
    EXEC SQL END DECLARE SECTION;

    if (!key || !out_amount)
        return TX_EINVAL;
    strncpy(h_key, key, sizeof(h_key) - 1);
    h_key[sizeof(h_key) - 1] = '\0';

    EXEC SQL SELECT dr_amt
        INTO :h_val
        FROM lg_ledger_line
        WHERE ledger_key = :h_key;

    if (sqlca.sqlcode == TX_SQL_NOTFOUND)
        return TX_ENOENT;
    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("lg_io_0019_fetch");
        return TX_EDB;
    }
    *out_amount = h_val;
    return TX_OK;
}

int lg_io_0019_touch(const char *key, long amount)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_key[32];
    long h_amt;
    EXEC SQL END DECLARE SECTION;

    if (!key)
        return TX_EINVAL;
    strncpy(h_key, key, sizeof(h_key) - 1);
    h_key[sizeof(h_key) - 1] = '\0';
    h_amt = amount;

    EXEC SQL UPDATE lg_ledger_line
        SET cr_amt = :h_amt
        WHERE ledger_key = :h_key AND dr_amt >= :h_amt;
    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("lg_io_0019_touch");
        return TX_EDB;
    }
    if (sqlca.sqlerrd[2] == 0)
        return TX_ENOENT;
    return TX_OK;
}

long lg_io_0019_total(const char *biz_date)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_dt[16];
    long h_grp;
    EXEC SQL END DECLARE SECTION;

    if (!biz_date)
        return -1;
    strncpy(h_dt, biz_date, sizeof(h_dt) - 1);
    h_dt[sizeof(h_dt) - 1] = '\0';

    long acc = 0;

    EXEC SQL DECLARE lg_io_0019_total_cur CURSOR FOR
        SELECT coalesce(sum(dr_amt), 0) FROM lg_ledger_line
        WHERE post_dt = :h_dt GROUP BY gl_acct;
    EXEC SQL OPEN lg_io_0019_total_cur;
    for (;;) {
        EXEC SQL FETCH lg_io_0019_total_cur INTO :h_grp;
        if (sqlca.sqlcode == TX_SQL_NOTFOUND)
            break;
        if (sqlca.sqlcode != TX_SQL_OK) {
            TX_DBIO_LOG_ERR("lg_io_0019_total");
            EXEC SQL CLOSE lg_io_0019_total_cur;
            return -1;
        }
        acc += h_grp;
    }
    EXEC SQL CLOSE lg_io_0019_total_cur;
    return acc;
}
