/* @tier easy @module mm @transform master-online */
/*
 * mm_ol_0030.pgc - 가맹점 상태조회 서비스 (MM_OL_0030)  [tier=easy]
 *
 * 가맹점번호로 mm_merchant 의 현재 상태코드와 최종변경일시(upd_date)를
 * 조회하여 상태코드/상태명/최종변경일을 응답한다. 조회 전용(읽기) 서비스.
 * (마스터 참조)
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

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

EXEC SQL INCLUDE sqlca;

TX_SERVICE(MM_OL_0030, ctx)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_merch_id[16];
    char h_status[2];
    char h_upd_date[9];
    EXEC SQL END DECLARE SECTION;

    char merch_id[16];
    char status_nm[16];

    tx_log(TX_LOG_INFO, "[MM_OL_0030] 가맹점 상태조회 서비스 진입");

    if (tx_buf_get(ctx->in, "MERCHID", merch_id, sizeof(merch_id)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[MM_OL_0030] MERCHID 누락");
        tx_buf_sets(ctx->out, "ERRCODE", "MM3000");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

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

    EXEC SQL
        SELECT status, COALESCE(upd_date, reg_date)
          INTO :h_status, :h_upd_date
          FROM mm_merchant
         WHERE merch_id = :h_merch_id;

    if (sqlca.sqlcode == TX_SQL_NOTFOUND) {
        tx_log(TX_LOG_WARN, "[MM_OL_0030] 가맹점 없음 merch=%s", merch_id);
        tx_buf_sets(ctx->out, "ERRCODE", RESP_NOMERCH);
        tx_return(ctx, TX_ENOENT, ctx->out);
        return;
    }
    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("SELECT mm_merchant status");
        tx_buf_sets(ctx->out, "ERRCODE", "MM3009");
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }

    if (strcmp(h_status, MM_ST_RECV) == 0)
        strncpy(status_nm, "접수", sizeof(status_nm) - 1);
    else if (strcmp(h_status, MM_ST_DONE) == 0)
        strncpy(status_nm, "정상", sizeof(status_nm) - 1);
    else if (strcmp(h_status, MM_ST_FAIL) == 0)
        strncpy(status_nm, "해지", sizeof(status_nm) - 1);
    else if (strcmp(h_status, MM_ST_SETTLED) == 0)
        strncpy(status_nm, "정산완료", sizeof(status_nm) - 1);
    else
        strncpy(status_nm, "기타", sizeof(status_nm) - 1);

    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "MERCHID", merch_id);
    tx_buf_sets(ctx->out, "STATUS", h_status);
    tx_buf_sets(ctx->out, "STATUSNM", status_nm);
    tx_buf_sets(ctx->out, "LASTCHG", h_upd_date);
    tx_buf_sets(ctx->out, "ERRCODE", RESP_OK);
    tx_log(TX_LOG_INFO, "[MM_OL_0030] 상태조회 완료 merch=%s status=%s(%s)",
           merch_id, h_status, status_nm);
    tx_return(ctx, TX_OK, ctx->out);
}
