package com.red.circle.console.app.command.rocket;

import com.red.circle.console.app.dto.clienobject.RocketConfigCO;
import com.red.circle.console.app.dto.cmd.RocketConfigQueryCmd;
import com.red.circle.framework.dto.ResultResponse;
import com.red.circle.other.inner.endpoint.rocket.RocketConfigClient;
import com.red.circle.other.inner.model.dto.rocket.RocketConfigDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 火箭配置查询执行器
 *
 * @author system
 * @date 2025-01-15
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class RocketConfigQueryExe {
    
    private final RocketConfigClient rocketConfigClient;
    
    /**
     * 查询所有配置
     */
    public List<RocketConfigCO> queryAll(RocketConfigQueryCmd cmd) {
        ResultResponse<List<RocketConfigDTO>> response = rocketConfigClient.queryAll(cmd.getStatus());
        
        if (!response.checkSuccess() || response.getBody() == null) {
            throw new RuntimeException("查询火箭配置失败: " + response.getErrorMsg());
        }
        
        return response.getBody().stream()
                .map(this::toConfigCO)
                .collect(Collectors.toList());
    }
    
    /**
     * 根据ID查询
     */
    public RocketConfigCO queryById(Long id) {
        ResultResponse<RocketConfigDTO> response = rocketConfigClient.queryById(id);
        
        if (!response.checkSuccess() || response.getBody() == null) {
            throw new RuntimeException("查询火箭配置失败: " + response.getErrorMsg());
        }
        
        return toConfigCO(response.getBody());
    }
    
    /**
     * DTO转CO
     */
    private RocketConfigCO toConfigCO(RocketConfigDTO dto) {
        if (dto == null) {
            return null;
        }
        
        RocketConfigCO co = new RocketConfigCO();
        co.setId(dto.getId());
        co.setLevel(dto.getLevel());
        co.setLevelName(getLevelName(dto.getLevel()));
        co.setMaxEnergy(dto.getMaxEnergy());
        co.setRewardConfig(dto.getRewardConfig());
        co.setContributorRewardRate(dto.getContributorRewardRate());
        co.setNormalRewardConfig(dto.getNormalRewardConfig());
        co.setStatus(dto.getStatus());
        co.setStatusDesc(dto.getStatus() == 1 ? "启用" : "禁用");
        co.setCreatedAt(dto.getCreatedAt());
        co.setUpdatedAt(dto.getUpdatedAt());
        
        return co;
    }
    
    /**
     * 获取等级名称
     */
    private String getLevelName(Integer level) {
        if (level == null) {
            return "";
        }
        return switch (level) {
            case 1 -> "一级火箭";
            case 2 -> "二级火箭";
            case 3 -> "三级火箭";
            default -> "未知等级";
        };
    }
}
