package tech.easyflow.common.web.multipart;

import org.junit.Assert;
import org.junit.Test;

/**
 * {@link MultipartFileMetadataNormalizer} 回归测试。
 */
public class MultipartFileMetadataNormalizerTest {

    /**
     * 验证合法媒体类型会被保留。
     */
    @Test
    public void shouldKeepValidDeclaredContentType() {
        Assert.assertEquals(
                "application/pdf",
                MultipartFileMetadataNormalizer.normalizeContentType(
                        "report.pdf",
                        "application/pdf"));
    }

    /**
     * 验证客户端占位值会按扩展名推断。
     */
    @Test
    public void shouldInferContentTypeWhenClientSendsOther() {
        Assert.assertEquals(
                "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                MultipartFileMetadataNormalizer.normalizeContentType(
                        "report.docx",
                        "Other"));
    }

    /**
     * 验证空媒体类型也会按扩展名推断。
     */
    @Test
    public void shouldInferContentTypeWhenClientOmitsIt() {
        Assert.assertEquals(
                "application/pdf",
                MultipartFileMetadataNormalizer.normalizeContentType(
                        "report.pdf",
                        "  "));
    }

    /**
     * 验证非法媒体类型且无法推断时使用二进制兜底。
     */
    @Test
    public void shouldFallbackToOctetStreamForUnknownFile() {
        Assert.assertEquals(
                "application/octet-stream",
                MultipartFileMetadataNormalizer.normalizeContentType(
                        "payload.unknown-extension",
                        "invalid content type"));
    }

    /**
     * 验证文件名不会携带客户端目录片段。
     */
    @Test
    public void shouldRemoveClientPathFromFilename() {
        Assert.assertEquals(
                "report.pdf",
                MultipartFileMetadataNormalizer.sanitizeFilename(
                        "C:\\fakepath\\report.pdf"));
    }

    /**
     * 验证超长文件名截断后仍保留可用于 MIME 推断的扩展名。
     */
    @Test
    public void shouldKeepExtensionWhenSanitizingLongFilename() {
        String filename = "a".repeat(300) + ".pdf";

        String sanitized =
                MultipartFileMetadataNormalizer.sanitizeFilename(
                        filename);

        Assert.assertEquals(255, sanitized.length());
        Assert.assertTrue(sanitized.endsWith(".pdf"));
        Assert.assertEquals(
                "application/pdf",
                MultipartFileMetadataNormalizer.normalizeContentType(
                        sanitized,
                        "Other"));
    }
}
