package com.ruoyi.lsfx.util;

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.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
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 HttpUtilTest {

    @Mock
    private RestTemplate restTemplate;

    @TempDir
    Path tempDir;

    @Test
    void uploadFile_shouldUseExplicitResourceFilename() throws Exception {
        HttpUtil httpUtil = new HttpUtil();
        ReflectionTestUtils.setField(httpUtil, "restTemplate", restTemplate);

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

        ArgumentCaptor<HttpEntity> captor = ArgumentCaptor.forClass(HttpEntity.class);
        when(restTemplate.postForEntity(eq("http://lsfx/upload"), captor.capture(), eq(String.class)))
            .thenReturn(ResponseEntity.ok("ok"));

        Map<String, Object> params = new HashMap<>();
        params.put("groupId", 200);
        params.put("files", HttpUtil.namedFileResource(tempFile.toFile(), "银行流水A.xlsx"));

        String result = httpUtil.uploadFile("http://lsfx/upload", params, null, String.class);

        assertEquals("ok", result);
        MultiValueMap<String, Object> body = (MultiValueMap<String, Object>) captor.getValue().getBody();
        Object filePart = body.getFirst("files");
        Resource resource = assertInstanceOf(Resource.class, filePart);
        assertEquals("银行流水A.xlsx", resource.getFilename());
    }
}
