package com.iqser.red.persistence.service.v1.external.api.impl.interceptors;

import static com.iqser.red.service.persistence.management.v1.processor.utils.DownloadBufferUtils.DOWNLOAD_TEMP_FILE_BUFFER_LOCATION;

import java.io.File;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class DownloadTempFileInterceptor implements HandlerInterceptor {

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

        String tempFileLocation = (String) request.getAttribute(DOWNLOAD_TEMP_FILE_BUFFER_LOCATION);
        if (tempFileLocation != null && tempFileLocation.length() > 0) {
            var file = new File(tempFileLocation);
            if (file.exists() && !file.delete()) {
                log.debug("Failed to delete file: {}", file.getAbsolutePath());
            }
        }

    }

}
