package io.apicurio.tests.serdes.apicurio.debezium.mysql;

import io.apicurio.tests.serdes.apicurio.debezium.DebeziumLocalConvertersUtil;
import io.apicurio.tests.serdes.apicurio.debezium.SharedDebeziumInfrastructure;
import io.apicurio.tests.serdes.apicurio.debezium.KubernetesDebeziumContainerWrapper;
import io.debezium.testing.testcontainers.DebeziumContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testcontainers.containers.MySQLContainer;

import java.util.Collections;
import java.util.Map;

/**
 * Container resource for Debezium MySQL integration tests that uses locally built
 * Apicurio converters instead of downloading them from Maven Central.
 */
public class DebeziumMySQLLocalConvertersResource extends DebeziumMySQLContainerResource {

    private static final Logger log = LoggerFactory.getLogger(DebeziumMySQLLocalConvertersResource.class);

    // Shadow parent's static fields to avoid pollution between regular and local-converter tests
    public static MySQLContainer<?> mysqlContainer;
    public static DebeziumContainer debeziumContainer;

    @Override
    public Map<String, String> start() {
        if (Boolean.parseBoolean(System.getProperty("cluster.tests"))) {
            log.info("cluster.tests=true detected for MySQL LOCAL CONVERTERS test");
            log.info("Debezium infrastructure with local converters should already be deployed");

            mysqlContainer = new KubernetesMySQLContainerWrapper(
                    io.apicurio.deployment.KubernetesTestResources.MYSQL_DEBEZIUM_SERVICE_EXTERNAL);
            debeziumContainer = new KubernetesDebeziumContainerWrapper(
                    io.apicurio.deployment.KubernetesTestResources.DEBEZIUM_CONNECT_LOCAL_SERVICE_EXTERNAL);

            log.info("Debezium MySQL service wrappers created for cluster mode using LOCAL converters");
            return Collections.emptyMap();
        }

        log.info("cluster.tests=false, using SharedDebeziumInfrastructure with local converters for MySQL");

        // Initialize shared infrastructure
        SharedDebeziumInfrastructure.initializeMySQLInfrastructure();

        // Get references from shared infrastructure
        mysqlContainer = SharedDebeziumInfrastructure.mysqlContainer;
        debeziumContainer = SharedDebeziumInfrastructure.debeziumContainerMysql;

        // Mount local converters on the shared Debezium container
        // This should only be done once when the container is first created
        DebeziumLocalConvertersUtil.mountLocalConverters(debeziumContainer);

        log.info("Debezium MySQL infrastructure ready with local converters (using shared containers)");

        return Collections.emptyMap();
    }
}
