package com.mini.capi.config;


import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.resource.PathResourceResolver;

import java.io.IOException;

@Configuration
@RequiredArgsConstructor
public class WebMvcConfig implements WebMvcConfigurer {

    private final AuthInterceptor authInterceptor;


    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/login").setViewName("forward:/index.html");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/")
                .resourceChain(true)
                .addResolver(new PathResourceResolver() {
                    @Override
                    protected Resource getResource(String resourcePath, Resource location) throws IOException {
                        Resource requested = super.getResource(resourcePath, location);
                        // 文件存在就返回，不存在返回 index.html
                        return requested != null ? requested : new ClassPathResource("/static/index.html");
                    }
                });
    }


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authInterceptor)
                .addPathPatterns("/**") // 拦截所有请求
                .excludePathPatterns(
                        // ① 排除 Vue 静态资源（匹配 static 目录下所有 js/css/img 等）
                        "/js/**",
                        "/css/**",
                        "/img/**",
                        "/favicon.ico",
                        "/index.html", // 排除首页（Vue 入口）
                        "/assets/**", // 若 Vue 打包后有 assets 目录，需排除
                        "/resource/**", // 若有其他静态资源目录，需排除
                        "/cApi/index/**",

                        "/login",
                        "/Sys/login/**", // 你的登录接口（原 /Sys/login/** 缺少 /cApi 前缀，修复）
                        "/Sys/jobs/**", // 原路径补充 /cApi 前缀
                        "/Sys/hosts/**",
                        "/Sys/dbs/**",

                        "/cApi/swagger-ui/**",
                        "/cApi/v3/api-docs/**"
                );
    }
}