/* @tier easy @module lg @transform ledger-online */
/*
 * lg_ol_0012.pgc - 원장 온라인 서비스 (LG_OL_0012)  [tier=easy]
 *
 * 미결원장 조회: 요청 가맹점(MERCHID)의 미결 상태 원장을 집계한다.
 * 미결이란 접수(status='R') 또는 불일치/실패(status='U') 상태로,
 * 아직 확정/정산으로 넘어가지 못한 건을 뜻한다. 접수 미결과 실패
 * 미결을 각각 구분 집계하고, 두 상태를 합한 전체 미결 건수/금액과
 * 원화 표기 문자열을 함께 응답한다 (조회 전용).
 *
 * TxCore TX_SERVICE 엔트리. 요청 TXBUF 를 검증하고 lg_ledger 에
 * 직접 임베디드 SQL(singleton 집계) 을 수행한 뒤 응답을 구성한다.
 */
#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;

TX_SERVICE(LG_OL_0012, ctx)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_merch_id[16];
    char h_status[2];
    int  h_cnt;
    long h_sum;
    EXEC SQL END DECLARE SECTION;

    char merch[16];
    char wonbuf[32];
    long recv_cnt = 0, recv_sum = 0;
    long fail_cnt = 0, fail_sum = 0;
    long open_cnt = 0, open_sum = 0;
    long open_avg = 0;

    tx_log(TX_LOG_INFO, "[LG_OL_0012] 미결원장 조회 서비스 진입");

    /* ---- 1. 요청 필드 수신 및 검증 ---- */
    if (tx_buf_get(ctx->in, "MERCHID", merch, sizeof(merch)) != TX_OK ||
        merch[0] == '\0') {
        tx_log(TX_LOG_ERROR, "[LG_OL_0012] MERCHID 누락");
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_INVALID);
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    strncpy(h_merch_id, merch, sizeof(h_merch_id) - 1);
    h_merch_id[sizeof(h_merch_id) - 1] = '\0';

    /* ---- 2. 접수(R) 미결 집계 ---- */
    strncpy(h_status, LG_ST_RECV, sizeof(h_status) - 1);
    h_status[sizeof(h_status) - 1] = '\0';

    EXEC SQL SELECT count(*), coalesce(sum(amount), 0)
        INTO :h_cnt, :h_sum
        FROM lg_ledger
        WHERE merch_id = :h_merch_id
          AND status   = :h_status;

    if (sqlca.sqlcode != TX_SQL_OK && sqlca.sqlcode != TX_SQL_NOTFOUND) {
        TX_DBIO_LOG_ERR("LG_OL_0012 recv");
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }
    recv_cnt = (long)h_cnt;
    recv_sum = h_sum;

    /* ---- 3. 불일치/실패(U) 미결 집계 ---- */
    strncpy(h_status, LG_ST_FAIL, sizeof(h_status) - 1);
    h_status[sizeof(h_status) - 1] = '\0';

    EXEC SQL SELECT count(*), coalesce(sum(amount), 0)
        INTO :h_cnt, :h_sum
        FROM lg_ledger
        WHERE merch_id = :h_merch_id
          AND status   = :h_status;

    if (sqlca.sqlcode != TX_SQL_OK && sqlca.sqlcode != TX_SQL_NOTFOUND) {
        TX_DBIO_LOG_ERR("LG_OL_0012 fail");
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }
    fail_cnt = (long)h_cnt;
    fail_sum = h_sum;

    /* ---- 4. 전체 미결 합산, 건당 평균, 원화 표기 ---- */
    open_cnt = recv_cnt + fail_cnt;
    open_sum = recv_sum + fail_sum;
    if (open_cnt > 0)
        open_avg = open_sum / open_cnt;   /* 미결 건당 평균금액 */
    amount_format_won(open_sum, wonbuf, sizeof(wonbuf));

    /* ---- 5. 응답 구성 (미결 0건도 정상 응답) ---- */
    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "RESPCODE", RESP_OK);
    tx_buf_sets(ctx->out, "MERCHID", merch);
    tx_buf_setlong(ctx->out, "RECVCNT", recv_cnt);
    tx_buf_setlong(ctx->out, "RECVSUM", recv_sum);
    tx_buf_setlong(ctx->out, "FAILCNT", fail_cnt);
    tx_buf_setlong(ctx->out, "FAILSUM", fail_sum);
    tx_buf_setlong(ctx->out, "OPENCNT", open_cnt);
    tx_buf_setlong(ctx->out, "OPENSUM", open_sum);
    tx_buf_setlong(ctx->out, "OPENAVG", open_avg);
    tx_buf_sets(ctx->out, "OPENWON", wonbuf);
    tx_buf_sets(ctx->out, "HASOPEN", (open_cnt > 0) ? "Y" : "N");

    tx_log(TX_LOG_INFO,
           "[LG_OL_0012] 미결조회 merch=%s 접수=%ld건 실패=%ld건 계=%ld건 금액=%s",
           merch, recv_cnt, fail_cnt, open_cnt, wonbuf);
    tx_return(ctx, TX_OK, ctx->out);
}
