package com.ruoyi.lsfx.client;

import com.ruoyi.lsfx.constants.LsfxConstants;
import com.ruoyi.lsfx.domain.response.UploadFileResponse;
import com.ruoyi.lsfx.util.HttpUtil;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.core.io.Resource;
import org.springframework.test.util.ReflectionTestUtils;

import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;

@ExtendWith(MockitoExtension.class)
class LsfxAnalysisClientTest {

    @Mock
    private HttpUtil httpUtil;

    @InjectMocks
    private LsfxAnalysisClient client;

    @TempDir
    Path tempDir;

    @Test
    void uploadFile_shouldPassOriginalFilenameToMultipartResource() throws Exception {
        ReflectionTestUtils.setField(client, "baseUrl", "http://lsfx");
        ReflectionTestUtils.setField(client, "uploadFileEndpoint", "/upload");
        ReflectionTestUtils.setField(client, "clientId", "client-1");

        Path tempFile = tempDir.resolve("batch_0_123456.xlsx");
        Files.writeString(tempFile, "content");

        UploadFileResponse response = new UploadFileResponse();
        response.setData(new UploadFileResponse.UploadData());

        ArgumentCaptor<Map<String, Object>> paramsCaptor = ArgumentCaptor.forClass(Map.class);
        ArgumentCaptor<Map<String, String>> headersCaptor = ArgumentCaptor.forClass(Map.class);
        when(httpUtil.uploadFile(eq("http://lsfx/upload"), paramsCaptor.capture(), headersCaptor.capture(), eq(UploadFileResponse.class)))
            .thenReturn(response);

        client.uploadFile(200, tempFile.toFile(), "银行流水A.xlsx");

        assertEquals(200, paramsCaptor.getValue().get("groupId"));
        Resource filePart = assertInstanceOf(Resource.class, paramsCaptor.getValue().get("files"));
        assertEquals("银行流水A.xlsx", filePart.getFilename());
        assertEquals("client-1", headersCaptor.getValue().get(LsfxConstants.HEADER_CLIENT_ID));
    }
}
