package ru.kirillius.pf.sdn.core;

import lombok.SneakyThrows;

import java.io.Closeable;
import java.lang.reflect.ParameterizedType;

/**
 * Defines the contract for pluggable application components with type-safe configuration access.
 */
public interface Component<CT> extends Closeable {
    /**
     * Resolves the configuration type parameter for a component implementation.
     */
    @SuppressWarnings("unchecked")
    static <T> Class<T> getConfigClass(Class<? extends Component<T>> pluginClass) {
        var genericSuperclass = (ParameterizedType) pluginClass.getGenericSuperclass();
        var typeArguments = genericSuperclass.getActualTypeArguments();
        return (Class<T>) typeArguments[0];
    }

    /**
     * Instantiates a component using its context-aware constructor.
     */
    @SneakyThrows
    static <T extends Component<?>> T loadPlugin(Class<T> pluginClass, Context context) {
        return pluginClass.getConstructor(Context.class).newInstance(context);
    }
}
