package de.accso.flexinale.common.infrastructure.eventbus;

import de.accso.flexinale.common.api.event.Event;
import de.accso.flexinale.common.shared_kernel.EventClassHelper;
import org.apache.kafka.clients.admin.AdminClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import static de.accso.flexinale.common.infrastructure.eventbus.KafkaConfiguration.adminConfig;
import static de.accso.flexinale.common.infrastructure.eventbus.KafkaConfiguration.kafkaTimeoutInMs;

@SuppressWarnings("unused")
public final class KafkaTopicHelper {
    private static final Logger LOGGER = LoggerFactory.getLogger(KafkaTopicHelper.class);

    static <E extends Event> String createTopicNameFromEventClazz(final Class<E> eventType) {
        return EventClassHelper.getEventClazzName(eventType)
                + ".v"
                + EventClassHelper.getEventClazzVersion(eventType).version();
    }

    static <E extends Event> String createTopicNameFromEventClazzAndInstance(final Class<E> eventType, final Event event) {
        return eventType.getCanonicalName()
                + ".v"
                + event.version().version();
    }

    public static void deleteKafkaTopicsWithPrefixAndSuffix(final String prefix, final String suffix)
            throws ExecutionException, TimeoutException
    {
        Map<String, Object> kafkaAdminConfig = adminConfig();

        try (var adminClient = AdminClient.create( kafkaAdminConfig )) {
            List<String> topicNames = adminClient.listTopics().names().get()
                    .stream()
                    .filter(name -> name.startsWith(prefix) && name.endsWith(suffix))
                    .toList();
            adminClient.deleteTopics(topicNames).all().get(kafkaTimeoutInMs, TimeUnit.SECONDS);

            if (topicNames.isEmpty()) {
                LOGGER.info("did not delete any Kafka topics");
            }
            else {
                LOGGER.info("tried to delete these Kafka topics: " + topicNames);
            }
        }
        catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
        }
    }
}
