package com.unicorn.hgzero.stt.config;

import com.unicorn.hgzero.stt.event.publisher.EventPublisher;
import com.unicorn.hgzero.stt.repository.jpa.RecordingRepository;
import com.unicorn.hgzero.stt.repository.jpa.SpeakerRepository;
import com.unicorn.hgzero.stt.repository.jpa.TranscriptionRepository;
import com.unicorn.hgzero.stt.repository.jpa.TranscriptSegmentRepository;
import com.unicorn.hgzero.stt.service.RecordingService;
import com.unicorn.hgzero.stt.service.SpeakerService;
import com.unicorn.hgzero.stt.service.TranscriptionService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import redis.embedded.RedisServer;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;

import static org.mockito.Mockito.mock;

/**
 * 테스트용 설정 클래스
 * Embedded Redis 서버와 Mock Bean들을 제공
 */
@TestConfiguration
@EnableJpaRepositories(basePackages = "com.unicorn.hgzero.stt.repository.jpa")
@EntityScan(basePackages = "com.unicorn.hgzero.stt.repository.entity")
@ComponentScan(basePackages = {"com.unicorn.hgzero.stt.service", "com.unicorn.hgzero.stt.config"})
public class TestConfig {

    private RedisServer redisServer;

    @PostConstruct
    public void startRedis() {
        try {
            redisServer = new RedisServer(6370);
            redisServer.start();
        } catch (Exception e) {
            // Redis 서버 시작 실패 시 로그만 남기고 계속 진행
            System.err.println("Failed to start embedded Redis server: " + e.getMessage());
        }
    }

    @PreDestroy
    public void stopRedis() {
        if (redisServer != null && redisServer.isActive()) {
            redisServer.stop();
        }
    }

    @Bean
    @Primary
    public EventPublisher eventPublisher() {
        return mock(EventPublisher.class);
    }



    @Bean
    @Primary
    @ConditionalOnMissingBean
    public RedisConnectionFactory redisConnectionFactory() {
        // Embedded Redis에 연결하는 실제 ConnectionFactory
        return new LettuceConnectionFactory("localhost", 6370);
    }

    @Bean
    @Primary
    @ConditionalOnMissingBean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        return template;
    }
}