package com.mvrent.carrental.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.multipart.support.MultipartFilter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.file.Paths;

/** Serves uploaded files from the configurable storage directory. */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Value("${app.storage.location}")
    private String location;

    @Value("${app.storage.url-prefix}")
    private String urlPrefix;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String base = urlPrefix.endsWith("/") ? urlPrefix : urlPrefix + "/";
        String fileUri = Paths.get(location).toAbsolutePath().normalize().toUri().toString();
        registry.addResourceHandler(base + "**").addResourceLocations(fileUri);
    }

    /**
     * Parse multipart requests before Spring Security so the CSRF token in a
     * multipart form body can be read (otherwise uploads fail with 403).
     */
    @Bean
    public FilterRegistrationBean<MultipartFilter> multipartFilterRegistration() {
        FilterRegistrationBean<MultipartFilter> registration =
                new FilterRegistrationBean<>(new MultipartFilter());
        registration.setOrder(Ordered.HIGHEST_PRECEDENCE);
        registration.addUrlPatterns("/*");
        return registration;
    }
}
