/*
 * cl_snapshot_dbio.pgc - 마감 스냅샷(snapshot) DB 접근 (part of libcldbio.a).
 * ECPG functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 */
#include <string.h>
#include <userlog.h>
#include "cl_dbio.h"

long cldb_next_snapshot_id(void)
{
    EXEC SQL BEGIN DECLARE SECTION;
    long h_id;
    EXEC SQL END DECLARE SECTION;

    EXEC SQL SELECT nextval('cl_snapshot_seq') INTO :h_id;
    if (sqlca.sqlcode < 0) {
        userlog("cldb_next_snapshot_id FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc);
        return -1;
    }
    return h_id;
}

int cldb_insert_snapshot(long sid, long cid, const char *period, const char *bizdate,
                         const char *merch, long gross, long fee, long net, long cnt)
{
    EXEC SQL BEGIN DECLARE SECTION;
    long h_sid = sid, h_cid = cid, h_gross = gross, h_fee = fee, h_net = net, h_cnt = cnt;
    char h_period[16], h_bizdate[16], h_merch[64];
    EXEC SQL END DECLARE SECTION;

    strncpy(h_period, period, sizeof(h_period) - 1);   h_period[sizeof(h_period)-1] = 0;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1);   h_bizdate[sizeof(h_bizdate)-1] = 0;
    strncpy(h_merch, merch, sizeof(h_merch) - 1);      h_merch[sizeof(h_merch)-1] = 0;

    EXEC SQL INSERT INTO cl_snapshot
        (snapshot_id, close_id, period_key, biz_date, merchant_id,
         gross_amount, fee_amount, net_amount, txn_count)
        VALUES (:h_sid, :h_cid, :h_period, :h_bizdate, :h_merch,
                :h_gross, :h_fee, :h_net, :h_cnt);
    if (sqlca.sqlcode < 0) {
        userlog("cldb_insert_snapshot FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc);
        return -1;
    }
    return 0;
}
