package com.mosquito.project.config;

import com.mosquito.project.persistence.repository.ApiKeyRepository;
import com.mosquito.project.security.UserIntrospectionService;
import com.mosquito.project.web.UserAuthInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    private final com.mosquito.project.web.ApiKeyAuthInterceptor apiKeyAuthInterceptor;
    private final com.mosquito.project.web.RateLimitInterceptor rateLimitInterceptor;
    private final com.mosquito.project.web.ApiResponseWrapperInterceptor responseWrapperInterceptor;
    private final UserAuthInterceptor userAuthInterceptor;

    public WebMvcConfig(ApiKeyRepository apiKeyRepository, org.springframework.core.env.Environment env, java.util.Optional<StringRedisTemplate> redisTemplateOpt, com.mosquito.project.web.ApiResponseWrapperInterceptor responseWrapperInterceptor, UserIntrospectionService userIntrospectionService) {
        this.apiKeyAuthInterceptor = new com.mosquito.project.web.ApiKeyAuthInterceptor(apiKeyRepository);
        this.rateLimitInterceptor = new com.mosquito.project.web.RateLimitInterceptor(env, redisTemplateOpt.orElse(null));
        this.responseWrapperInterceptor = responseWrapperInterceptor;
        this.userAuthInterceptor = new UserAuthInterceptor(userIntrospectionService);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(responseWrapperInterceptor)
            .addPathPatterns("/api/**");
        registry.addInterceptor(apiKeyAuthInterceptor)
            .addPathPatterns("/api/**")
            .excludePathPatterns("/r/**", "/actuator/**");
        registry.addInterceptor(rateLimitInterceptor)
            .addPathPatterns("/api/v1/callback/register");
        registry.addInterceptor(userAuthInterceptor)
            .addPathPatterns(
                "/api/v1/me/**",
                "/api/v1/activities/**",
                "/api/v1/api-keys/**",
                "/api/v1/share/**"
            );
    }
}
