/* @tier easy @module lg @transform ledger-online */
/*
 * lg_ol_0030.pgc - 원장 온라인 서비스 (LG_OL_0030)  [tier=easy]
 *
 * 매출 집계반영: 지정 영업일의 실거래(요약행 제외) Σamount/건수를 집계하여
 * 요약행(key=영업일, merch_id='*SUMMARY', status=S) 을 새로 INSERT 한다.
 */
#include <stdio.h>
#include <string.h>

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

EXEC SQL INCLUDE sqlca;

#define LG_OL_0030_SUMMARY_ID "*SUMMARY"

/*
 * [업무 개요]
 *   특정 영업일의 실거래 매출을 집계하여 원장에 "요약행" 한 건으로 반영한다.
 *   요약행은 merch_id='*SUMMARY', status='S', key=영업일 규칙을 따르며, 집계
 *   시에는 기존 요약행을 제외하여 이중집계를 방지한다.
 *
 * [멱등성]
 *   같은 영업일에 재실행되어도 결과가 동일하도록, 기존 요약행(key=영업일) 을
 *   먼저 DELETE 한 뒤 새 요약행을 INSERT 한다. (delete-then-insert)
 *
 * [처리 절차]
 *   1) BIZDATE 추출/검증.
 *   2) 실거래(merch_id<>'*SUMMARY') Σamount/건수 집계.
 *   3) tx_begin → 기존 요약행 DELETE → 신규 요약행 INSERT → tx_commit.
 *
 * [응답 필드]
 *   RESPCODE  처리결과코드   BIZDATE 영업일(에코)   SUMKEY 요약행 key
 *   TOTAL     집계 합계금액   CNT 집계 대상 건수
 */
TX_SERVICE(LG_OL_0030, ctx)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_biz_date[9];
    char h_sum_id[16];
    char h_status_s[2];
    char h_key[16];
    long h_total;
    long h_cnt;
    EXEC SQL END DECLARE SECTION;

    char bizdate[16];

    tx_log(TX_LOG_INFO, "[LG_OL_0030] 매출 집계반영 진입");

    if (tx_buf_get(ctx->in, "BIZDATE", bizdate, sizeof(bizdate)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[LG_OL_0030] 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, "[LG_OL_0030] 영업일 형식 오류 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';
    strncpy(h_sum_id, LG_OL_0030_SUMMARY_ID, sizeof(h_sum_id) - 1);
    h_sum_id[sizeof(h_sum_id) - 1] = '\0';
    strncpy(h_status_s, LG_ST_SETTLED, sizeof(h_status_s) - 1);
    h_status_s[sizeof(h_status_s) - 1] = '\0';
    strncpy(h_key, bizdate, sizeof(h_key) - 1);   /* 요약행 key = 영업일 */
    h_key[sizeof(h_key) - 1] = '\0';

    /* 실거래만 집계 (요약행 자체는 제외) */
    EXEC SQL SELECT coalesce(sum(amount), 0), count(*)
        INTO :h_total, :h_cnt
        FROM lg_ledger
        WHERE biz_date = :h_biz_date
          AND merch_id <> :h_sum_id;
    if (sqlca.sqlcode != TX_SQL_OK && sqlca.sqlcode != TX_SQL_NOTFOUND) {
        TX_DBIO_LOG_ERR("lg_ol_0030 aggregate");
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }

    if (tx_begin() != TX_OK) {
        tx_return(ctx, TX_FAIL, ctx->out);
        return;
    }

    /* 기존 요약행 제거 후 재삽입 (멱등) */
    EXEC SQL DELETE FROM lg_ledger WHERE key = :h_key;
    if (sqlca.sqlcode != TX_SQL_OK && sqlca.sqlcode != TX_SQL_NOTFOUND) {
        TX_DBIO_LOG_ERR("lg_ol_0030 delete old");
        tx_abort();
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }

    EXEC SQL INSERT INTO lg_ledger
        (key, merch_id, card_no, amount, biz_date, status, fee)
        VALUES
        (:h_key, :h_sum_id, '', :h_total, :h_biz_date, :h_status_s, 0);
    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("lg_ol_0030 insert summary");
        tx_abort();
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }

    if (tx_commit() != TX_OK) {
        tx_abort();
        tx_return(ctx, TX_FAIL, ctx->out);
        return;
    }

    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, "SUMKEY", h_key);
    tx_buf_setlong(ctx->out, "TOTAL", h_total);
    tx_buf_setlong(ctx->out, "CNT", h_cnt);
    tx_log(TX_LOG_INFO, "[LG_OL_0030] 집계반영 완료 date=%s 합계=%ld 건수=%ld",
           bizdate, h_total, h_cnt);
    tx_return(ctx, TX_OK, ctx->out);
}
