package com.haha.admin.config;

import com.haha.common.config.LogProperties;
import com.haha.common.constant.LogConstants;
import com.haha.common.interceptor.RequestLogInterceptor;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * Web MVC 配置类
 * 用于配置拦截器、跨域、静态资源等
 *
 * @author haha
 */
@Configuration(proxyBeanMethods = false)
@RequiredArgsConstructor
public class WebMvcConfig implements WebMvcConfigurer {

    private final RequestLogInterceptor requestLogInterceptor;

    private final LogProperties logProperties;

    @Value("${upload.path:./upload}")
    private String uploadPath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 映射上传目录为静态资源，解析为绝对路径
        Path path = Paths.get(uploadPath);
        if (!path.isAbsolute()) {
            path = Paths.get(System.getProperty("user.dir")).resolve(uploadPath).normalize();
        }
        String absolutePath = path.toAbsolutePath().toString().replace("\\", "/");
        if (!absolutePath.endsWith("/")) {
            absolutePath += "/";
        }
        registry.addResourceHandler("/upload/**")
                .addResourceLocations("file:" + absolutePath);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册请求日志拦截器
        if (logProperties.getEnableRequestLog()) {
            registry.addInterceptor(requestLogInterceptor)
                    .addPathPatterns("/**")
                    .excludePathPatterns(LogConstants.EXCLUDE_PATHS);
        }
    }
}
