package com.samsung.interceptor;

import com.samsung.resource.FileManagerException;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.Collection;
import java.util.List;

@Log4j2
public class UploadFileExtensionCheckInterceptor implements HandlerInterceptor {

    private String allowedExtensions;

    @Value("${common.upload.allowed-extensions}")
    public void setAllowedExtensions(String allowedExtensions) {
        this.allowedExtensions = allowedExtensions.toLowerCase();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        if (request instanceof MultipartRequest) {
            MultipartRequest req = ((MultipartRequest) request);
            Collection<List<MultipartFile>> multiFiles = req.getMultiFileMap().values();
            for (List<MultipartFile> fileList : multiFiles) {
                for (MultipartFile file : fileList) {
                    String fileName = file.getOriginalFilename();
                    String fileExt = "";
                    if (fileName != null) {
                        fileExt = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
                    }
                    if (!isAllowedExtension(fileExt)) {
                        throw new FileManagerException("Not allowed file extension: " + fileName);
                    }
                }
            }
        }
        return true;
    }

    private boolean isAllowedExtension(String fileExt) {
        return allowedExtensions.contains(fileExt);
    }
}
