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

import com.fasterxml.jackson.core.type.TypeReference;
import com.ycwl.basic.integration.common.exception.IntegrationException;
import com.ycwl.basic.integration.common.response.CommonResponse;
import com.ycwl.basic.integration.common.service.IntegrationFallbackService;
import com.ycwl.basic.integration.scenic.client.ScenicV2Client;
import com.ycwl.basic.integration.scenic.dto.config.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class ScenicConfigIntegrationService {

    private final ScenicV2Client scenicConfigV2Client;
    private final IntegrationFallbackService fallbackService;
    
    private static final String SERVICE_NAME = "zt-scenic";

    /**
     * 获取景区配置列表（带降级，使用TypeReference保留泛型信息）
     */
    public List<ScenicConfigV2DTO> listConfigs(Long scenicId) {
        log.debug("获取景区配置列表, scenicId: {}", scenicId);
        return fallbackService.executeWithFallback(
            SERVICE_NAME,
            "scenic:configs:" + scenicId,
            () -> {
                CommonResponse<List<ScenicConfigV2DTO>> response = scenicConfigV2Client.listConfigs(scenicId);
                return handleResponse(response, "获取景区配置列表失败");
            },
            new TypeReference<List<ScenicConfigV2DTO>>() {}
        );
    }

    public ScenicConfigV2DTO getConfigByKey(Long scenicId, String configKey) {
        log.debug("根据键获取景区配置, scenicId: {}, configKey: {}", scenicId, configKey);
        return fallbackService.executeWithFallback(
            SERVICE_NAME,
            "scenic:config:" + scenicId + ":" + configKey,
            () -> {
                CommonResponse<ScenicConfigV2DTO> response = scenicConfigV2Client.getConfigByKey(scenicId, configKey);
                return handleResponse(response, "根据键获取景区配置失败");
            },
            ScenicConfigV2DTO.class
        );
    }

    public ScenicConfigV2DTO createConfig(Long scenicId, CreateConfigRequest request) {
        log.debug("创建景区配置, scenicId: {}, configKey: {}", scenicId, request.getConfigKey());
        CommonResponse<ScenicConfigV2DTO> response = scenicConfigV2Client.createConfig(scenicId, request);
        ScenicConfigV2DTO result = handleResponse(response, "创建景区配置失败");
        // 清理配置列表缓存
        clearConfigCache(scenicId, request.getConfigKey());
        return result;
    }

    public ScenicConfigV2DTO updateConfig(Long scenicId, String id, UpdateConfigRequest request) {
        log.debug("更新景区配置, scenicId: {}, id: {}", scenicId, id);
        CommonResponse<ScenicConfigV2DTO> response = scenicConfigV2Client.updateConfig(scenicId, id, request);
        ScenicConfigV2DTO result = handleResponse(response, "更新景区配置失败");
        // 清理配置相关缓存
        clearConfigCache(scenicId, request.getConfigKey());
        return result;
    }

    public void deleteConfig(Long scenicId, String id) {
        log.debug("删除景区配置, scenicId: {}, id: {}", scenicId, id);
        CommonResponse<Void> response = scenicConfigV2Client.deleteConfig(scenicId, id);
        handleResponse(response, "删除景区配置失败");
        // 清理配置列表缓存（无法确定具体key，清理整个列表缓存）
        fallbackService.clearFallbackCache(SERVICE_NAME, "scenic:configs:" + scenicId);
    }

    public BatchUpdateResponse batchUpdateConfigs(Long scenicId, BatchConfigRequest request) {
        log.debug("批量更新景区配置, scenicId: {}, configs count: {}", scenicId, request.getConfigs().size());
        CommonResponse<BatchUpdateResponse> response = scenicConfigV2Client.batchUpdateConfigs(scenicId, request);
        BatchUpdateResponse result = handleResponse(response, "批量更新景区配置失败");
        // 清理所有相关缓存
        clearAllConfigCache(scenicId);
        return result;
    }

    /**
     * 清理指定配置的缓存
     */
    private void clearConfigCache(Long scenicId, String configKey) {
        fallbackService.clearFallbackCache(SERVICE_NAME, "scenic:configs:" + scenicId);
        if (configKey != null) {
            fallbackService.clearFallbackCache(SERVICE_NAME, "scenic:config:" + scenicId + ":" + configKey);
        }
    }

    /**
     * 清理景区所有配置相关缓存
     */
    private void clearAllConfigCache(Long scenicId) {
        fallbackService.clearFallbackCache(SERVICE_NAME, "scenic:configs:" + scenicId);
    }


    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();
    }
}