package com.ycwl.basic.integration.scenic.service;

import com.ycwl.basic.integration.common.exception.IntegrationException;
import com.ycwl.basic.integration.common.response.CommonResponse;
import com.ycwl.basic.integration.scenic.client.ScenicV2Client;
import com.ycwl.basic.integration.scenic.dto.config.DefaultConfigDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class ScenicDefaultConfigIntegrationService {

    private final ScenicV2Client defaultConfigClient;

    public List<DefaultConfigDTO> listDefaultConfigs() {
        log.debug("获取默认配置列表");
        CommonResponse<List<DefaultConfigDTO>> response = defaultConfigClient.listDefaultConfigs();
        return handleResponse(response, "获取默认配置列表失败");
    }

    public DefaultConfigDTO getDefaultConfig(String configKey) {
        log.debug("获取指定默认配置, configKey: {}", configKey);
        CommonResponse<DefaultConfigDTO> response = defaultConfigClient.getDefaultConfig(configKey);
        return handleResponse(response, "获取指定默认配置失败");
    }

    public DefaultConfigDTO createDefaultConfig(DefaultConfigDTO request) {
        log.debug("创建默认配置, configKey: {}", request.getConfigKey());
        CommonResponse<DefaultConfigDTO> response = defaultConfigClient.createDefaultConfig(request);
        return handleResponse(response, "创建默认配置失败");
    }

    public DefaultConfigDTO updateDefaultConfig(String configKey, DefaultConfigDTO request) {
        log.debug("更新默认配置, configKey: {}", configKey);
        CommonResponse<DefaultConfigDTO> response = defaultConfigClient.updateDefaultConfig(configKey, request);
        return handleResponse(response, "更新默认配置失败");
    }

    public void deleteDefaultConfig(String configKey) {
        log.debug("删除默认配置, configKey: {}", configKey);
        CommonResponse<Void> response = defaultConfigClient.deleteDefaultConfig(configKey);
        handleResponse(response, "删除默认配置失败");
    }

    private <T> T handleResponse(CommonResponse<T> response, String errorMessage) {
        if (response == null || !response.isSuccess()) {
            String msg = response != null && response.getMessage() != null 
                        ? response.getMessage() 
                        : errorMessage;
            Integer code = response != null ? response.getCode() : 5000;
            throw new IntegrationException(code, msg, "zt-scenic");
        }
        return response.getData();
    }
}