package com.arms.egovframework.javaservice.esframework.repository.common;

import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Component
@AllArgsConstructor
public class FindRepository {

    private final List<EsCommonRepository<?, ? extends Serializable>> repositories;

    public <T, U extends Serializable> EsCommonRepository<T, U> findRepositoryByClass(Object clazz) {
        return repositories.stream()
                .filter(repo -> {
                    Type[] genericInterfaces = repo.getClass().getGenericInterfaces();
                    List<Type> collect = Arrays.stream(genericInterfaces)
                            .flatMap(type -> {
                                Type[] generics = ((Class<?>)type).getGenericInterfaces();
                                return Arrays.stream(generics)
                                        .filter(ParameterizedType.class::isInstance)
                                        .filter(generic -> ((ParameterizedType)generic).getActualTypeArguments()[0].equals(clazz));
                            }).toList();
                    return !collect.isEmpty();
                })
                .map(repo-> (EsCommonRepository<T, U>)repo)
                .findFirst()
                .orElseThrow(()->new IllegalArgumentException("타입이 존재 하지 않습니다."));
    }
}
