package com.gcsc.connection.common.service;

import com.gcsc.connection.common.dto.SystemConfigResponse;
import com.gcsc.connection.common.dto.UpdateSystemConfigRequest;
import com.gcsc.connection.common.entity.SnpSystemConfig;
import com.gcsc.connection.common.repository.SnpSystemConfigRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
@RequiredArgsConstructor
public class SystemConfigService {

    private final SnpSystemConfigRepository systemConfigRepository;

    /**
     * 설정 값 단건 조회
     */
    @Transactional(readOnly = true)
    public SystemConfigResponse getConfigValue(String configKey) {
        return systemConfigRepository.findByConfigKey(configKey)
            .map(SystemConfigResponse::from)
            .orElse(null);
    }

    /**
     * 설정 값 저장 (upsert: 없으면 생성, 있으면 수정)
     */
    @Transactional
    public SystemConfigResponse updateConfig(String configKey, UpdateSystemConfigRequest request) {
        SnpSystemConfig config = systemConfigRepository.findByConfigKey(configKey)
            .map(existing -> {
                existing.update(request.configValue());
                return existing;
            })
            .orElseGet(() -> systemConfigRepository.save(
                SnpSystemConfig.builder()
                    .configKey(configKey)
                    .configValue(request.configValue())
                    .build()
            ));
        log.info("시스템 설정 저장: configKey={}", configKey);
        return SystemConfigResponse.from(config);
    }
}
