/* @tier easy @module cl @transform closing-online */
/*
 * cl_ol_0008.pgc - 마감 온라인 서비스 (CL_OL_0008)  [tier=easy]
 *
 * 마감 스냅샷 생성. 요청 영업일(BIZDATE)의 집계(건수/금액합계/수수료합계)를
 * 산출한 뒤, 그 결과를 cl_ledger 에 요약행(스냅샷)으로 INSERT 한다.
 * 스냅샷 행 규약: key=BIZDATE+'SS', merch_id='*SNAP', amount=Σamount,
 * fee=Σfee, status='S'. 동일 스냅샷이 이미 있으면 경고로 응답한다.
 */
#include <stdio.h>
#include <string.h>

#include "txcore.h"
#include "txcore_dbio.h"
#include "acq_util.h"
#include "cl_core.h"

EXEC SQL INCLUDE sqlca;

TX_SERVICE(CL_OL_0008, ctx)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_biz_date[9];
    char h_snap_key[16];
    int  h_cnt;
    long h_amt_sum;
    long h_fee_sum;
    int  h_exist;
    EXEC SQL END DECLARE SECTION;

    char bizdate[16];

    tx_log(TX_LOG_INFO, "[CL_OL_0008] 마감 스냅샷 생성 서비스 진입");

    /* 1. 요청 검증 */
    if (tx_buf_get(ctx->in, "BIZDATE", bizdate, sizeof(bizdate)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[CL_OL_0008] BIZDATE 누락");
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_INVALID);
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }
    if (!date_is_valid(bizdate)) {
        tx_log(TX_LOG_WARN, "[CL_OL_0008] 영업일 형식 오류 date=%s", bizdate);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_INVALID);
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    strncpy(h_biz_date, bizdate, sizeof(h_biz_date) - 1);
    h_biz_date[sizeof(h_biz_date) - 1] = '\0';
    /* 스냅샷 채번키 = 영업일 + 'SS' */
    snprintf(h_snap_key, sizeof(h_snap_key), "%.8sSS", h_biz_date);

    /* 2. 스냅샷 중복 확인 */
    EXEC SQL SELECT count(*)
        INTO :h_exist
        FROM cl_ledger
        WHERE key = :h_snap_key;
    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("CL_OL_0008 snap exist");
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }
    if (h_exist > 0) {
        tx_log(TX_LOG_WARN, "[CL_OL_0008] 스냅샷 기존재 key=%s", h_snap_key);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_INVALID);
        tx_buf_sets(ctx->out, "SNAPKEY", h_snap_key);
        tx_buf_sets(ctx->out, "MESSAGE", "동일 영업일 스냅샷 기존재");
        tx_return(ctx, TX_FAIL, ctx->out);
        return;
    }

    /* 3. 실거래(스냅샷 제외) 집계 : 건수 / Σamount / Σfee */
    EXEC SQL SELECT count(*),
                    coalesce(sum(amount), 0),
                    coalesce(sum(fee), 0)
        INTO :h_cnt, :h_amt_sum, :h_fee_sum
        FROM cl_ledger
        WHERE biz_date = :h_biz_date
          AND merch_id <> '*SNAP';
    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("CL_OL_0008 aggregate");
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }

    /* 4. 스냅샷 요약행 INSERT (트랜잭션) */
    if (tx_begin() != TX_OK) {
        tx_log(TX_LOG_ERROR, "[CL_OL_0008] 트랜잭션 시작 실패");
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
        tx_return(ctx, TX_FAIL, ctx->out);
        return;
    }

    EXEC SQL INSERT INTO cl_ledger
        (key, merch_id, card_no, amount, biz_date, status, fee, upd_ts)
        VALUES
        (:h_snap_key, '*SNAP', '', :h_amt_sum, :h_biz_date, 'S', :h_fee_sum, now());
    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("CL_OL_0008 snap insert");
        tx_abort();
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }

    tx_commit();

    /* 5. 응답 구성 */
    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "RESPCODE", RESP_OK);
    tx_buf_sets(ctx->out, "BIZDATE", bizdate);
    tx_buf_sets(ctx->out, "SNAPKEY", h_snap_key);
    tx_buf_setlong(ctx->out, "SNAPCNT", (long)h_cnt);
    tx_buf_setlong(ctx->out, "SNAPAMT", h_amt_sum);
    tx_buf_setlong(ctx->out, "SNAPFEE", h_fee_sum);
    tx_log(TX_LOG_INFO, "[CL_OL_0008] 스냅샷 생성 key=%s 건수=%d 금액=%ld",
           h_snap_key, h_cnt, h_amt_sum);
    tx_return(ctx, TX_OK, ctx->out);
}
