/* @tier easy @module cl @transform closing-online */
/*
 * cl_ol_0019.pgc - 마감 온라인 서비스 (CL_OL_0019)  [tier=easy]
 *
 * 마감 취소 승인
 * ----------------------------------------------------------------------
 * 요청 KEY 의 원장이 취소요청 상태(status='U')인지 확인한 뒤, 승인되면
 * 처리완료(status='M') 로 재개방 갱신한다. 대상이 취소요청 상태가
 * 아니면 승인 불가로 반려한다. 상태 조회 후 갱신은 하나의 트랜잭션으로
 * 커밋하며, 승인/반려 결과와 원거래 요약(가맹점/금액/영업일)을 응답에
 * 함께 실어 상위 화면이 감사표시를 할 수 있게 한다. 감사추적을 위해
 * 선택 입력 REQID/OPER 를 로그·응답에 반영한다.
 */
#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_0019, ctx)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_key[16];
    char h_prev_st[2];
    char h_new_st[2];
    char h_oper[32];
    char h_reqid[32];
    EXEC SQL END DECLARE SECTION;

    cl_rec_t rec;
    char key[16];
    char reqid[32];
    char oper[32];
    char won[32];
    int  rc;

    tx_log(TX_LOG_INFO, "[CL_OL_0019] 마감 취소 승인 서비스 진입");

    /* 1) 입력 수신 */
    if (tx_buf_get(ctx->in, "KEY", key, sizeof(key)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[CL_OL_0019] KEY 누락");
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_INVALID);
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }
    if (tx_buf_get(ctx->in, "REQID", reqid, sizeof(reqid)) != TX_OK)
        strncpy(reqid, "-", sizeof(reqid) - 1);
    if (tx_buf_get(ctx->in, "OPER", oper, sizeof(oper)) != TX_OK)
        strncpy(oper, "SUPERV", sizeof(oper) - 1);

    /* 2) 현재 상태 조회 */
    memset(&rec, 0, sizeof(rec));
    rc = cl_rec_select(key, &rec);
    if (rc == TX_ENOENT) {
        tx_log(TX_LOG_WARN, "[CL_OL_0019] 대상없음 key=%s reqid=%s", key, reqid);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_INVALID);
        tx_buf_sets(ctx->out, "APPROVED", "N");
        tx_buf_sets(ctx->out, "MESSAGE", "취소승인 대상 원장 없음");
        tx_return(ctx, TX_ENOENT, ctx->out);
        return;
    }
    if (rc != TX_OK) {
        tx_log(TX_LOG_ERROR, "[CL_OL_0019] 조회 실패 key=%s rc=%d", key, rc);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
        tx_return(ctx, rc, ctx->out);
        return;
    }

    /* 3) 취소요청(U) 상태만 승인 가능 */
    if (strcmp(rec.status, CL_ST_FAIL) != 0) {
        tx_log(TX_LOG_WARN, "[CL_OL_0019] 승인불가 상태 key=%s status=%s reqid=%s",
               key, rec.status, reqid);
        amount_format_won(rec.amount, won, sizeof(won));
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_INVALID);
        tx_buf_sets(ctx->out, "APPROVED", "N");
        tx_buf_sets(ctx->out, "KEY", key);
        tx_buf_sets(ctx->out, "STATUS", rec.status);
        tx_buf_sets(ctx->out, "MERCHID", rec.merch_id);
        tx_buf_setlong(ctx->out, "AMOUNT", rec.amount);
        tx_buf_sets(ctx->out, "AMOUNTWON", won);
        tx_buf_sets(ctx->out, "MESSAGE", "취소요청(U) 상태가 아니어서 승인 불가");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    /* 4) 재개방 승인: U -> M 갱신 (트랜잭션) */
    if (tx_begin() != TX_OK) {
        tx_log(TX_LOG_ERROR, "[CL_OL_0019] 트랜잭션 시작 실패 key=%s", key);
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
        tx_return(ctx, TX_FAIL, ctx->out);
        return;
    }

    rc = cl_rec_update_status(key, CL_ST_DONE);
    if (rc != TX_OK) {
        tx_log(TX_LOG_ERROR, "[CL_OL_0019] 승인갱신 실패 key=%s rc=%d", key, rc);
        tx_abort();
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
        tx_buf_sets(ctx->out, "APPROVED", "N");
        tx_return(ctx, rc, ctx->out);
        return;
    }

    /* 취소 승인 감사이력 적재 (동일 트랜잭션) */
    strncpy(h_key, key, sizeof(h_key) - 1);
    h_key[sizeof(h_key) - 1] = '\0';
    strncpy(h_prev_st, CL_ST_FAIL, sizeof(h_prev_st));
    strncpy(h_new_st, CL_ST_DONE, sizeof(h_new_st));
    strncpy(h_oper, oper, sizeof(h_oper) - 1);
    h_oper[sizeof(h_oper) - 1] = '\0';
    strncpy(h_reqid, reqid, sizeof(h_reqid) - 1);
    h_reqid[sizeof(h_reqid) - 1] = '\0';

    EXEC SQL INSERT INTO cl_cancel_audit
            (key, prev_status, new_status, oper, reqid, chg_ts)
        VALUES (:h_key, :h_prev_st, :h_new_st, :h_oper, :h_reqid, now());

    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("CL_OL_0019 INSERT cl_cancel_audit");
        tx_abort();
        tx_buf_reset(ctx->out);
        tx_buf_sets(ctx->out, "RESPCODE", RESP_SYSERR);
        tx_buf_sets(ctx->out, "APPROVED", "N");
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }

    tx_commit();

    /* 5) 승인 결과 응답 (원거래 요약 포함) */
    amount_format_won(rec.amount, won, sizeof(won));
    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, "REQID", reqid);
    tx_buf_sets(ctx->out, "OPER", oper);
    tx_buf_sets(ctx->out, "APPROVED", "Y");
    tx_buf_sets(ctx->out, "PREVSTATUS", CL_ST_FAIL);
    tx_buf_sets(ctx->out, "STATUS", CL_ST_DONE);
    tx_buf_sets(ctx->out, "MERCHID", rec.merch_id);
    tx_buf_sets(ctx->out, "BIZDATE", rec.biz_date);
    tx_buf_setlong(ctx->out, "AMOUNT", rec.amount);
    tx_buf_sets(ctx->out, "AMOUNTWON", won);
    tx_buf_sets(ctx->out, "MESSAGE", "마감 취소 승인(재개방) 완료");

    tx_log(TX_LOG_INFO, "[CL_OL_0019] 취소 승인 완료 key=%s U->M oper=%s reqid=%s",
           key, oper, reqid);
    tx_return(ctx, TX_OK, ctx->out);
}
