/*
 * cl_openclose_dbio.pgc - 일/월/분기/연 공용 마감 집계+이력생성 (part of libcldbio.a).
 * ECPG functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 * CL_DAILY/MONTHLY/QUARTER/YEAREND 서비스가 공유한다. (예전 cl_svr 인라인
 * static cl_open_close 를 dbio 계층으로 이전; EXEC SQL 은 .pgc 에서만 허용됨.)
 */
#include <string.h>
#include <userlog.h>
#include "cl_dbio.h"

int cldb_open_close(const char *ctype, const char *period, const char *bizdate,
                    long *cid_out, long *cnt_out, long *amt_out)
{
    EXEC SQL BEGIN DECLARE SECTION;
    long h_cnt, h_amt, h_cid;
    char h_bizdate[16], h_type[16], h_period[16];
    EXEC SQL END DECLARE SECTION;

    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    strncpy(h_type, ctype, sizeof(h_type)-1); h_type[sizeof(h_type)-1] = 0;

    if (strcmp(ctype, "DAILY") == 0) {
        EXEC SQL SELECT count(*), coalesce(sum(amount), 0) INTO :h_cnt, :h_amt
            FROM purchase WHERE biz_date = :h_bizdate;
    } else {
        strncpy(h_period, period, sizeof(h_period)-1); h_period[sizeof(h_period)-1] = 0;
        EXEC SQL SELECT count(*), coalesce(sum(amount), 0) INTO :h_cnt, :h_amt
            FROM purchase WHERE to_char(biz_date, 'YYYY-MM') LIKE :h_period || '%';
    }
    if (sqlca.sqlcode < 0) {
        userlog("cldb_open_close agg FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc);
        return -1;
    }

    h_cid = cldb_next_close_id();
    if (h_cid < 0) return -1;
    if (cldb_insert_close(h_cid, ctype, period, bizdate, "C", h_cnt, h_amt, "마감") < 0) return -1;
    *cid_out = h_cid;
    *cnt_out = h_cnt;
    *amt_out = h_amt;
    return 0;
}
