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

import com.ycwl.basic.integration.common.exception.IntegrationException;
import com.ycwl.basic.integration.common.response.CommonResponse;
import com.ycwl.basic.integration.common.response.PageResponse;
import com.ycwl.basic.integration.common.service.IntegrationFallbackService;
import com.ycwl.basic.integration.render.client.RenderWorkerV2Client;
import com.ycwl.basic.integration.render.dto.worker.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * 渲染工作器集成服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class RenderWorkerIntegrationService {

    private final RenderWorkerV2Client renderWorkerV2Client;
    private final IntegrationFallbackService fallbackService;
    
    private static final String SERVICE_NAME = "zt-render-worker";

    /**
     * 获取工作器核心信息（带降级）
     */
    public RenderWorkerV2DTO getWorker(Long id) {
        log.debug("获取渲染工作器信息, id: {}", id);
        return fallbackService.executeWithFallback(
            SERVICE_NAME,
            "worker:" + id,
            () -> {
                CommonResponse<RenderWorkerV2DTO> response = renderWorkerV2Client.getWorker(id);
                return handleResponse(response, "获取渲染工作器信息失败");
            },
            RenderWorkerV2DTO.class
        );
    }

    /**
     * 创建工作器（直接调用，不降级）
     */
    public RenderWorkerV2DTO createWorker(CreateRenderWorkerRequest request) {
        log.debug("创建渲染工作器, name: {}, key: {}", request.getName(), request.getKey());
        CommonResponse<RenderWorkerV2DTO> response = renderWorkerV2Client.createWorker(request);
        return handleResponse(response, "创建渲染工作器失败");
    }

    /**
     * 更新工作器（直接调用，不降级）
     */
    public void updateWorker(Long id, UpdateRenderWorkerRequest request) {
        log.debug("更新渲染工作器, id: {}, name: {}", id, request.getName());
        CommonResponse<Void> response = renderWorkerV2Client.updateWorker(id, request);
        handleVoidResponse(response, "更新渲染工作器失败");
        // 清理工作器相关缓存
        fallbackService.clearFallbackCache(SERVICE_NAME, "worker:" + id);
    }

    /**
     * 删除工作器（直接调用，不降级）
     */
    public void deleteWorker(Long id) {
        log.debug("删除渲染工作器, id: {}", id);
        CommonResponse<Void> response = renderWorkerV2Client.deleteWorker(id);
        handleVoidResponse(response, "删除渲染工作器失败");
        // 清理工作器相关缓存
        fallbackService.clearFallbackCache(SERVICE_NAME, "worker:" + id);
    }

    /**
     * 分页查询工作器列表（核心信息）（不降级）
     */
    public PageResponse<RenderWorkerV2DTO> listWorkers(Integer page, Integer pageSize, Integer isEnabled, String name) {
        log.debug("分页查询渲染工作器列表, page: {}, pageSize: {}, isEnabled: {}, name: {}", 
                 page, pageSize, isEnabled, name);
        CommonResponse<PageResponse<RenderWorkerV2DTO>> response = 
            renderWorkerV2Client.listWorkers(page, pageSize, isEnabled, name);
        return handleResponse(response, "查询渲染工作器列表失败");
    }

    /**
     * 根据key获取工作器核心信息（带降级）
     */
    public RenderWorkerV2DTO getWorkerByKey(String key) {
        log.debug("根据key获取渲染工作器信息, key: {}", key);
        return fallbackService.executeWithFallback(
            SERVICE_NAME,
            "worker:key:" + key,
            () -> {
                CommonResponse<RenderWorkerV2DTO> response = renderWorkerV2Client.getWorkerByKey(key);
                return handleResponse(response, "根据key获取渲染工作器信息失败");
            },
            RenderWorkerV2DTO.class
        );
    }

    /**
     * 处理通用响应
     */
    private <T> T handleResponse(CommonResponse<T> response, String errorMessage) {
        if (response == null || !response.getSuccess()) {
            String msg = response != null && response.getMessage() != null ? 
                        response.getMessage() : errorMessage;
            Integer code = response != null ? response.getCode() : 5000;
            throw new IntegrationException(code, msg, SERVICE_NAME);
        }
        return response.getData();
    }

    /**
     * 处理空响应
     */
    private void handleVoidResponse(CommonResponse<Void> response, String errorMessage) {
        if (response == null || !response.getSuccess()) {
            String msg = response != null && response.getMessage() != null ? 
                        response.getMessage() : errorMessage;
            Integer code = response != null ? response.getCode() : 5000;
            throw new IntegrationException(code, msg, SERVICE_NAME);
        }
    }

}