package com.example.demo.config;

import java.util.Locale;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.CacheControl;
import org.springframework.web.servlet.LocaleResolver;
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 org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import com.example.demo.interceptor.UserActivityInterceptor;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

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

    @Autowired
    private UserActivityInterceptor userActivityInterceptor;

    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver slr = new SessionLocaleResolver();
        slr.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);
        return slr;
    }

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
        lci.setParamName("lang");
        return lci;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 语言切换拦截器
        registry.addInterceptor(localeChangeInterceptor());
        
        // 用户活跃时间更新拦截器（用于统计在线用户）
        registry.addInterceptor(userActivityInterceptor)
                .addPathPatterns("/**") // 拦截所有请求
                .excludePathPatterns(
                    "/css/**", 
                    "/js/**", 
                    "/images/**", 
                    "/uploads/**",
                    "/favicon.ico",
                    "/error"
                ); // 排除静态资源
    }

    /**
     * 配置静态资源服务，使上传的文件可以通过URL访问
     * 访问路径：/uploads/** -> 映射到 uploads/ 目录
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 将 /uploads/** 映射到 uploads/ 目录
        // 处理路径：如果是相对路径，转换为绝对路径；如果是绝对路径，直接使用
        java.nio.file.Path uploadDirPath = java.nio.file.Paths.get(uploadPath);
        if (!uploadDirPath.isAbsolute()) {
            // 相对路径：基于应用运行目录
            uploadDirPath = java.nio.file.Paths.get(System.getProperty("user.dir"), uploadPath);
        }
        
        // 确保路径使用正斜杠（URL格式）
        String resourceLocation = "file:" + uploadDirPath.toAbsolutePath().toString().replace("\\", "/") + "/";
        
        // 上传文件缓存7天（视频/图片等媒体文件）
        registry.addResourceHandler("/uploads/**")
                .addResourceLocations(resourceLocation)
                .setCacheControl(CacheControl.maxAge(7, TimeUnit.DAYS).cachePublic());
        
        // 静态资源缓存配置（JS/CSS/图片等）
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/")
                .setCacheControl(CacheControl.maxAge(30, TimeUnit.DAYS).cachePublic());
        
        // 图片资源缓存30天
        registry.addResourceHandler("/images/**")
                .addResourceLocations("classpath:/static/images/")
                .setCacheControl(CacheControl.maxAge(30, TimeUnit.DAYS).cachePublic());
    }

    // CORS配置已移至SecurityConfig，避免冲突
}



