package tech.easyflow.log.reporter;

import jakarta.servlet.http.HttpServletResponse;
import org.junit.Test;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.util.Map;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

/**
 * {@link ActionReportInterceptor} Multipart 日志安全测试。
 */
public class ActionReportInterceptorTest {

    /**
     * 验证 Multipart 日志只读取 Part 元数据，不读取原始请求体。
     *
     * @throws Exception 构造处理器或日志回调失败
     */
    @Test
    public void multipartReportShouldNotReadRawRequestBody()
            throws Exception {
        ActionReportInterceptor interceptor =
                new ActionReportInterceptor(
                        new ActionLogReporterProperties());
        MultipartHttpServletRequest request =
                mock(MultipartHttpServletRequest.class);
        HttpServletResponse response = mock(HttpServletResponse.class);
        MultipartFile file = mock(MultipartFile.class);
        LinkedMultiValueMap<String, MultipartFile> files =
                new LinkedMultiValueMap<>();
        files.add("files.document", file);
        when(request.getMethod()).thenReturn("POST");
        when(request.getRequestURI())
                .thenReturn("/public-api/workflow/runAsync");
        when(request.getContentType())
                .thenReturn("multipart/form-data; boundary=test");
        when(request.getParameterMap()).thenReturn(Map.of());
        when(request.getMultiFileMap()).thenReturn(files);
        when(file.getOriginalFilename())
                .thenReturn("C:\\fakepath\\report.docx");
        when(file.getContentType()).thenReturn("Other");
        when(file.getSize()).thenReturn(128L);
        HandlerMethod handler = new HandlerMethod(
                new SampleController(),
                SampleController.class.getDeclaredMethod("run"));

        interceptor.preHandle(request, response, handler);
        interceptor.afterCompletion(
                request,
                response,
                handler,
                null);

        verify(request, never()).getInputStream();
    }

    /**
     * 提供测试用处理方法。
     */
    private static final class SampleController {

        /**
         * 测试处理方法。
         */
        private void run() {
        }
    }
}
