package com.reg.server.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.resource.PathResourceResolver;

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

@Configuration
public class PdfResourceConfig implements WebMvcConfigurer {

	@Value("${app.pdf.external-dir:}")
	private String externalDir;

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		String[] locations = resolveLocations();
		registry.addResourceHandler("/pdf/**")
				.addResourceLocations(locations)
				.resourceChain(true)
				.addResolver(new PathResourceResolver());
	}

	private String[] resolveLocations() {
		if (!StringUtils.hasText(externalDir)) {
			return new String[]{"classpath:/pdf/"};
		}

		String externalLocation = toExternalLocation(externalDir);
		return new String[]{externalLocation, "classpath:/pdf/"};
	}

	private static String toExternalLocation(String directory) {
		Path path = Paths.get(directory).toAbsolutePath().normalize();
		String uri = path.toUri().toString();
		return uri.endsWith("/") ? uri : (uri + "/");
	}
}
