/* @tier medium @module cl @transform closing-online */
/*
 * cl_ol_0016.pgc - 마감 온라인 서비스 (CL_OL_0016)  [tier=medium]
 *
 * 마감 확정. 요청 처리키(KEY) 단건에 대해 현재 상태를 확인한 뒤 처리완료(M)
 * 건을 정산완료(S)로 확정한다. 이미 정산완료(S)면 경고로 응답하고, 확정
 * 대상이 아닌 상태(R/U)이면 확정 불가로 응답한다. (singleton SELECT 후
 * 단건 UPDATE; tx_begin/tx_commit)
 */
#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_0016, ctx)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_key[16];
    char h_status[2];
    long h_amount;
    EXEC SQL END DECLARE SECTION;

    char key[16];
    char won[40];

    tx_log(TX_LOG_INFO, "[CL_OL_0016] 마감 확정 서비스 진입");

    /* 1. 요청 검증 : 처리키 필수 */
    if (tx_buf_get(ctx->in, "KEY", key, sizeof(key)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[CL_OL_0016] KEY 누락");
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_INVALID);
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    strncpy(h_key, key, sizeof(h_key) - 1);
    h_key[sizeof(h_key) - 1] = '\0';

    /* 2. 현재 상태/금액 단건 조회 (PK singleton SELECT) */
    EXEC SQL SELECT status, amount
        INTO :h_status, :h_amount
        FROM cl_ledger
        WHERE key = :h_key;
    if (sqlca.sqlcode == TX_SQL_NOTFOUND) {
        tx_log(TX_LOG_WARN, "[CL_OL_0016] 원장 없음 key=%s", key);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_INVALID);
        tx_buf_sets(ctx->out, "KEY", key);
        tx_buf_sets(ctx->out, "MESSAGE", "해당 처리키 원장 없음");
        tx_return(ctx, TX_ENOENT, ctx->out);
        return;
    }
    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("CL_OL_0016 status select");
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }
    h_status[1] = '\0';
    amount_format_won(h_amount, won, sizeof(won));

    /* 3. 이미 확정(S)인 경우 경고 응답 (멱등 처리) */
    if (strcmp(h_status, CL_ST_SETTLED) == 0) {
        tx_log(TX_LOG_WARN, "[CL_OL_0016] 이미 확정 key=%s", key);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_OK);
        tx_buf_sets(ctx->out, "KEY", key);
        tx_buf_sets(ctx->out, "STATUS", h_status);
        tx_buf_setlong(ctx->out, "AMOUNT", h_amount);
        tx_buf_sets(ctx->out, "CONFIRMED", "Y");
        tx_buf_sets(ctx->out, "MESSAGE", "이미 마감확정된 건");
        tx_return(ctx, TX_OK, ctx->out);
        return;
    }

    /* 4. 확정 대상은 처리완료(M) 만 허용 */
    if (strcmp(h_status, CL_ST_DONE) != 0) {
        tx_log(TX_LOG_WARN, "[CL_OL_0016] 확정 불가 상태 key=%s status=%s",
               key, h_status);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_INVALID);
        tx_buf_sets(ctx->out, "KEY", key);
        tx_buf_sets(ctx->out, "STATUS", h_status);
        tx_buf_sets(ctx->out, "CONFIRMED", "N");
        tx_buf_sets(ctx->out, "MESSAGE", "처리완료(M) 건만 확정 가능");
        tx_return(ctx, TX_FAIL, ctx->out);
        return;
    }

    /* 5. 확정 트랜잭션 : M → S 단건 UPDATE */
    if (tx_begin() != TX_OK) {
        tx_log(TX_LOG_ERROR, "[CL_OL_0016] 트랜잭션 시작 실패");
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
        tx_return(ctx, TX_FAIL, ctx->out);
        return;
    }

    EXEC SQL UPDATE cl_ledger
        SET status = 'S', upd_ts = now()
        WHERE key    = :h_key
          AND status = 'M';
    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("CL_OL_0016 confirm update");
        tx_abort();
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }
    if (sqlca.sqlerrd[2] == 0) {
        /* 조회~갱신 사이 상태 변동 (경합) → 롤백 후 경고 */
        tx_log(TX_LOG_WARN, "[CL_OL_0016] 확정 대상 소실(경합) key=%s", key);
        tx_abort();
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_INVALID);
        tx_buf_sets(ctx->out, "KEY", key);
        tx_buf_sets(ctx->out, "CONFIRMED", "N");
        tx_buf_sets(ctx->out, "MESSAGE", "확정 대상 상태 변동으로 실패");
        tx_return(ctx, TX_FAIL, ctx->out);
        return;
    }

    tx_commit();

    /* 6. 응답 구성 */
    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "RESPCODE", RESP_OK);
    tx_buf_sets(ctx->out, "KEY", key);
    tx_buf_sets(ctx->out, "STATUS", CL_ST_SETTLED);
    tx_buf_setlong(ctx->out, "AMOUNT", h_amount);
    tx_buf_sets(ctx->out, "AMOUNTWON", won);
    tx_buf_sets(ctx->out, "CONFIRMED", "Y");
    tx_log(TX_LOG_INFO, "[CL_OL_0016] 마감확정 완료 key=%s M→S 금액=%ld",
           key, h_amount);
    tx_return(ctx, TX_OK, ctx->out);
}
