/**
 * This file is part of the Meeds project (https://meeds.io/).
 *
 * Copyright (C) 2020 - 2025 Meeds Association contact@meeds.io
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */
package org.exoplatform.upload;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

import org.exoplatform.component.test.AbstractKernelTest;
import org.exoplatform.component.test.ConfigurationUnit;
import org.exoplatform.component.test.ConfiguredBy;
import org.exoplatform.component.test.ContainerScope;

import org.apache.commons.fileupload2.core.FileUploadException;
import org.junit.Test;
import org.mockito.Mockito;

import jakarta.servlet.http.HttpServletRequest;

@ConfiguredBy({
        @ConfigurationUnit(scope = ContainerScope.PORTAL, path = "conf/services/upload-service.xml")
})
public class TestUploadService extends AbstractKernelTest {
    private static final String tmpDir = System.getProperty("java.io.tmpdir");
    UploadService uploadService;

    @Override
    protected void beforeRunBare() {
        super.beforeRunBare();
        uploadService = getContainer().getComponentInstanceOfType(UploadService.class);
    }

    @Test
    public void testCorrectFileName() {
        String fileName;

        fileName = "test_abcdef0123456789.ext";
        fileName = uploadService.correctFileName(fileName);
        assertEquals("test_abcdef0123456789.ext", fileName);
        assertFileCreation(fileName);

        fileName = "test~`!@#$%^&*()-=+_.ext";
        fileName = uploadService.correctFileName(fileName);
        assertEquals("test~`!@#$%^&_()-=+_.ext", fileName);
        assertFileCreation(fileName);

        fileName = "test[]{}\\|.ext";
        fileName = uploadService.correctFileName(fileName);
        assertEquals("test[]{}__.ext", fileName);
        assertFileCreation(fileName);

        fileName = "test;:\"'.ext";
        fileName = uploadService.correctFileName(fileName);
        assertEquals("test;__'.ext", fileName);
        assertFileCreation(fileName);

        fileName = "test_tên tiếng việt.mở rộng";
        fileName = uploadService.correctFileName(fileName);
        assertEquals("test_tên tiếng việt.mở rộng", fileName);
        assertFileCreation(fileName);

        fileName = "test_越南人的名字。扩展";
        fileName = uploadService.correctFileName(fileName);
        assertEquals("test_越南人的名字。扩展", fileName);
        assertFileCreation(fileName);

        fileName = "test_В'єтнамські імена. розширення";
        fileName = uploadService.correctFileName(fileName);
        assertEquals("test_В'єтнамські імена. розширення", fileName);
        assertFileCreation(fileName);

        fileName = "test_베트남어 이름. 확장";
        fileName = uploadService.correctFileName(fileName);
        assertEquals("test_베트남어 이름. 확장", fileName);
        assertFileCreation(fileName);

        fileName = "test_वियतनामी नामों. विस्तार";
        fileName = uploadService.correctFileName(fileName);
        assertEquals("test_वियतनामी नामों. विस्तार", fileName);
        assertFileCreation(fileName);

        fileName = "test_ベトナム語名。拡大";
        fileName = uploadService.correctFileName(fileName);
        assertEquals("test_ベトナム語名。拡大", fileName);
        assertFileCreation(fileName);

        fileName = "test_ਵੀਅਤਨਾਮੀ ਨਾਮ. ਵਿਸਤਾਰ";
        fileName = uploadService.correctFileName(fileName);
        assertEquals("test_ਵੀਅਤਨਾਮੀ ਨਾਮ. ਵਿਸਤਾਰ", fileName);
        assertFileCreation(fileName);

        fileName = "test_Вьетнамские имена. расширение";
        fileName = uploadService.correctFileName(fileName);
        assertEquals("test_Вьетнамские имена. расширение", fileName);
        assertFileCreation(fileName);
    }

    public void testShouldNotCreateUploadResourceWhenUploadIdContainsDots() {
        String notAllowedUploadId = ".webapps.ROOT.123456";
        try {
            HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
            uploadService.createUploadResource(notAllowedUploadId, request);
            fail("The upload resource creation must fail with the id " + notAllowedUploadId);
        } catch(FileUploadException e) {
            assertEquals("Upload id " + notAllowedUploadId
                    + " is not valid, it cannot be null or contain '.' , '/' or '\\'", e.getMessage());
        }
    }

    public void testShouldNotCreateUploadResourceWhenUploadIdContainsSlashs() {
        String notAllowedUploadId = "/webapps/ROOT/123456";
        try {
            HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
            uploadService.createUploadResource(notAllowedUploadId, request);
            fail("The upload resource creation must fail with the id " + notAllowedUploadId);
        } catch(FileUploadException e) {
            assertEquals("Upload id " + notAllowedUploadId
                    + " is not valid, it cannot be null or contain '.' , '/' or '\\'", e.getMessage());
        }
    }

    public void testShouldNotCreateUploadResourceWhenUploadIdContainsAntiSlashs() {
        String notAllowedUploadId = "\\webapps\\ROOT\\123456";
        try {
            HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
            uploadService.createUploadResource(notAllowedUploadId, request);
            fail("The upload resource creation must fail with the id " + notAllowedUploadId);
        } catch(FileUploadException e) {
            assertEquals("Upload id " + notAllowedUploadId
                    + " is not valid, it cannot be null or contain '.' , '/' or '\\'", e.getMessage());
        }
    }

    @Test
    public void testShouldRejectUnsafeSvgUpload() throws Exception {
        SvgUploadValidator validator = new SvgUploadValidator();
        String unsafeSvg = "<svg xmlns=\"http://www.w3.org/2000/svg\" onload=\"alert(1)\"><rect width=\"10\" height=\"10\"/></svg>";

        try (InputStream inputStream = new ByteArrayInputStream(unsafeSvg.getBytes(StandardCharsets.UTF_8))) {
            validator.validate("infected.svg", "image/svg+xml", inputStream);
            fail("Unsafe SVG upload must be rejected");
        } catch (FileUploadException e) {
            assertEquals(SvgUploadValidator.INFECTED_SVG_MESSAGE, e.getMessage());
        }
    }

    @Test
    public void testSvgValidatorShouldNotSupportNonSvgFiles() {
        SvgUploadValidator validator = new SvgUploadValidator();

        assertFalse(validator.supports("document.xml", "application/xml"));
        assertFalse(validator.supports("page.html", "text/html"));
        assertFalse(validator.supports("presentation.pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"));
        assertFalse(validator.supports("spreadsheet.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
    }

    private void assertFileCreation(String fileName) {
        String file = tmpDir + File.separator + fileName;
        File f = new File(file);
        f.deleteOnExit();
        try {
            f.createNewFile();
        } catch (IOException ex) {
            fail("Can not create file with name: " + fileName);
        }
    }
}
