/* @tier medium @module cm @transform common-online */
/*
 * cm_ol_0017.pgc - 공통코드 목록 조회 서비스 (CM_OL_0017)  [tier=medium]
 *
 * 요청의 코드그룹(GRP)에 속한 전체 공통코드(cm_code)를 커서로 순회하며
 * "코드:코드명" 항목을 세미콜론 구분 목록 문자열로 누적 구성하여
 * 목록(LIST)과 건수(CNT)를 응답한다. 코드박스/드롭다운 조회 공통 서비스.
 * (ATMI void SVC(TPSVCINFO*) 대응)
 */
#include <stdio.h>
#include <string.h>

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

EXEC SQL INCLUDE sqlca;

TX_SERVICE(CM_OL_0017, ctx)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_grp[16];
    char h_code[16];
    char h_name[64];
    EXEC SQL END DECLARE SECTION;

    char grp[16];
    char list[1024];
    char item[96];
    long cnt = 0;
    int  truncated = 0;

    tx_log(TX_LOG_INFO, "[CM_OL_0017] 공통코드 목록 조회 서비스 진입");

    if (tx_buf_get(ctx->in, "GRP", grp, sizeof(grp)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[CM_OL_0017] GRP 누락");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    memset(h_grp, 0, sizeof(h_grp));
    strncpy(h_grp, grp, sizeof(h_grp) - 1);
    list[0] = '\0';

    EXEC SQL DECLARE cur_cm_ol_0017 CURSOR FOR
        SELECT code_cd, code_name
          FROM cm_code
         WHERE grp_cd = :h_grp
           AND use_yn = 'Y'
         ORDER BY sort_no, code_cd;

    EXEC SQL OPEN cur_cm_ol_0017;
    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("CM_OL_0017 OPEN cur_cm_ol_0017");
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }

    for (;;) {
        memset(h_code, 0, sizeof(h_code));
        memset(h_name, 0, sizeof(h_name));

        EXEC SQL FETCH cur_cm_ol_0017 INTO :h_code, :h_name;

        if (sqlca.sqlcode == TX_SQL_NOTFOUND)
            break;
        if (sqlca.sqlcode != TX_SQL_OK) {
            TX_DBIO_LOG_ERR("CM_OL_0017 FETCH cur_cm_ol_0017");
            EXEC SQL CLOSE cur_cm_ol_0017;
            tx_return(ctx, TX_EDB, ctx->out);
            return;
        }

        snprintf(item, sizeof(item), "%s:%s", h_code, h_name);

        /* 목록 버퍼 오버플로 방지: 구분자 포함 여유 확인 */
        if (strlen(list) + strlen(item) + 2 >= sizeof(list)) {
            truncated = 1;
            break;
        }
        if (cnt > 0)
            strncat(list, ";", sizeof(list) - strlen(list) - 1);
        strncat(list, item, sizeof(list) - strlen(list) - 1);
        cnt++;
    }

    EXEC SQL CLOSE cur_cm_ol_0017;

    if (cnt == 0) {
        tx_log(TX_LOG_WARN, "[CM_OL_0017] 코드 없음 grp=%s", grp);
        tx_return(ctx, TX_ENOENT, ctx->out);
        return;
    }

    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "GRP", grp);
    tx_buf_sets(ctx->out, "LIST", list);
    tx_buf_setlong(ctx->out, "CNT", cnt);
    tx_buf_sets(ctx->out, "TRUNCATED", truncated ? "Y" : "N");
    tx_log(TX_LOG_INFO, "[CM_OL_0017] 목록완료 grp=%s 건수=%ld 절단=%s",
           grp, cnt, truncated ? "Y" : "N");
    tx_return(ctx, TX_OK, ctx->out);
}
