package com.magistr.app.config.tenant;

import com.magistr.app.config.auth.AuthorizationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class TenantWebMvcConfig implements WebMvcConfigurer {

    private final TenantRoutingDataSource tenantRoutingDataSource;
    private final AuthorizationInterceptor authorizationInterceptor;

    public TenantWebMvcConfig(TenantRoutingDataSource tenantRoutingDataSource,
                              AuthorizationInterceptor authorizationInterceptor) {
        this.tenantRoutingDataSource = tenantRoutingDataSource;
        this.authorizationInterceptor = authorizationInterceptor;
    }

    @Bean
    public TenantInterceptor tenantInterceptor() {
        TenantInterceptor interceptor = new TenantInterceptor();
        interceptor.setRoutingDataSource(tenantRoutingDataSource);
        return interceptor;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(tenantInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/actuator/**");
        registry.addInterceptor(authorizationInterceptor).addPathPatterns("/api/**");
    }
}
