package com.infoepoch.pms.agent.platform.model.application;

import com.infoepoch.pms.agent.platform.model.domain.AiModelProvider;
import com.infoepoch.pms.agent.platform.model.domain.irepository.IAiModelConfigRepository;
import com.infoepoch.pms.agent.platform.model.domain.irepository.IAiModelProviderRepository;
import com.infoepoch.pms.agent.platform.model.domain.AiModelConfig;
import com.infoepoch.pms.agent.platform.shared.exception.BusinessException;
import com.infoepoch.pms.agent.platform.shared.response.ResultCode;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * 模型配置查询服务。
 */
@Service
@RequiredArgsConstructor
public class ModelQueryService {

    private final IAiModelConfigRepository modelConfigRepository;
    private final IAiModelProviderRepository modelProviderRepository;

    /**
     * 按 ID 查询模型配置。
     *
     * @param modelConfigId 模型配置 ID
     * @return 已补齐供应商实体的模型配置；ID 为空时返回空
     */
    @Transactional(readOnly = true)
    public Optional<AiModelConfig> findById(String modelConfigId) {
        if (modelConfigId == null) {
            return Optional.empty();
        }
        return modelConfigRepository.findById(modelConfigId)
                .map(this::attachProvider);
    }

    /**
     * 按 ID 查询模型配置。
     *
     * @param modelConfigId 模型配置 ID
     * @return 模型配置；当 ID 为空时返回 {@code null}
     * @throws BusinessException MODEL_CONFIG_NOT_FOUND 若模型配置不存在
     */
    @Transactional(readOnly = true)
    public AiModelConfig getModelConfigOrNull(String modelConfigId) {
        if (modelConfigId == null) {
            return null;
        }
        return findById(modelConfigId)
                .orElseThrow(() -> new BusinessException(ResultCode.MODEL_CONFIG_NOT_FOUND,
                        "模型配置 ID=" + modelConfigId + " 不存在"));
    }

    /**
     * 为模型配置补齐供应商实体。
     *
     * @param config 模型配置
     * @return 带供应商实体的模型配置
     */
    public AiModelConfig attachProvider(AiModelConfig config) {
        if (config == null || config.getProvider() != null || config.getProviderId() == null) {
            return config;
        }
        AiModelProvider provider = modelProviderRepository.findById(config.getProviderId())
                .orElseThrow(() -> new BusinessException(ResultCode.PROVIDER_NOT_FOUND,
                        "供应商 ID=" + config.getProviderId() + " 不存在"));
        config.setProvider(provider);
        return config;
    }
}
