package com.mosquito.project.config;

import org.springframework.boot.test.context.TestConfiguration;
import redis.embedded.RedisServer;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import java.io.IOException;
import java.net.ServerSocket;

@TestConfiguration
public class EmbeddedRedisConfiguration {

    private RedisServer redisServer;
    private int redisPort;

    @PostConstruct
    public void startRedis() throws IOException {
        redisPort = getAvailablePort();
        redisServer = new RedisServer(redisPort);
        redisServer.start();
        System.setProperty("spring.redis.port", String.valueOf(redisPort));
    }

    @PreDestroy
    public void stopRedis() {
        redisServer.stop();
    }

    private int getAvailablePort() throws IOException {
        try (ServerSocket serverSocket = new ServerSocket(0)) {
            return serverSocket.getLocalPort();
        }
    }
}
