package com.sourcefellows.bookingfellow.client;

import eu.rekawek.toxiproxy.Proxy;
import eu.rekawek.toxiproxy.ToxiproxyClient;
import eu.rekawek.toxiproxy.model.ToxicDirection;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class ToxiProxyConfiguerer {

    private final Logger logger = LoggerFactory.getLogger(ToxiProxyConfiguerer.class);

    private Proxy serviceProxy = null;

    @PostConstruct
    public void configureProxy() {

        logger.info("configure toxiProxy with timeout");

        try {
            ToxiproxyClient client = new ToxiproxyClient("127.0.0.1", 8474);
            serviceProxy = client.createProxy("service", "localhost:21212", "localhost:8080");
            serviceProxy.toxics().timeout("my-timeout", ToxicDirection.DOWNSTREAM, -1);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @PreDestroy
    public void close() {
        if (serviceProxy != null) {
            try {
                serviceProxy.delete();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

}
