package com.qmth.boot.api.config;

import com.qmth.boot.api.interceptor.ExtendInterceptor;
import com.qmth.boot.api.interceptor.impl.AuthorizationInterceptor;
import com.qmth.boot.api.interceptor.impl.MetricsInterceptor;
import com.qmth.boot.api.interceptor.impl.RateLimitInterceptor;
import com.qmth.boot.api.interceptor.impl.ValveInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

@Configuration
public class ApiInterceptorConfig implements WebMvcConfigurer {

    @Resource
    private ApiProperties apiProperties;

    @Resource
    private ValveInterceptor valveInterceptor;

    @Resource
    private RateLimitInterceptor rateLimitInterceptor;

    @Resource
    private MetricsInterceptor metricsInterceptor;

    @Resource
    private AuthorizationInterceptor authorizationInterceptor;

    private ExtendInterceptor extendInterceptor;

    @Autowired(required = false)
    public void setExtendInterceptor(ExtendInterceptor extendInterceptor) {
        this.extendInterceptor = extendInterceptor;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        String prefix = apiProperties.getUriPrefix();
        if (prefix.endsWith("/")) {
            prefix = prefix.concat("**");
        } else {
            prefix = prefix.concat("/**");
        }
        registry.addInterceptor(valveInterceptor).addPathPatterns(prefix);
        registry.addInterceptor(metricsInterceptor).addPathPatterns(prefix);
        registry.addInterceptor(authorizationInterceptor).addPathPatterns(prefix);
        registry.addInterceptor(rateLimitInterceptor).addPathPatterns(prefix);
        if (extendInterceptor != null) {
            registry.addInterceptor(extendInterceptor).addPathPatterns(prefix);
        }
    }
}
