package org.mte.numecoeval.referentiel.infrastructure.restapi.controller.facteurcaracterisation;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mte.numecoeval.referentiel.domain.exception.ReferentielException;
import org.mte.numecoeval.referentiel.infrastructure.adapter.export.FacteurCaracterisationCsvExportService;
import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.FacteurCaracterisationDTO;
import org.mte.numecoeval.referentiel.infrastructure.restapi.facade.FacteurCaracterisationFacade;
import org.mte.numecoeval.referentiel.utils.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpStatus;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.web.server.ResponseStatusException;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.List;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;


@ContextConfiguration(classes = {ReferentielFacteurCaracterisationRestApiImpl.class})
@ExtendWith(SpringExtension.class)

public class ReferentielFacteurCaracterisationRestApiImplTest {
    @Autowired
    private ReferentielFacteurCaracterisationRestApiImpl referentielRestApi;

    @MockBean
    private FacteurCaracterisationFacade referentielFacade;

    @MockBean
    private FacteurCaracterisationCsvExportService csvExportService;

    @Test
    void get_shouldCallFacadeGetAndReturnMatchingDTO() throws ReferentielException {
        String nom = "Ordinateur Portable";
        String nomOrganisation = "nomOrga";
        String nomCritere = "Changement Climatique";
        String codeEtapeACV = "UTILISATION";

        var fc = FacteurCaracterisationDTO.builder()
                .nom(nom)
                .etape(codeEtapeACV)
                .nomOrganisation(nomOrganisation)
                .critere(nomCritere)
                .niveau(Constants.EQUIPEMENT_NIVEAU)
                .valeur(1.0).build();

        var expectedDTO = List.of(fc);
        when(referentielFacade.getByFilters(nomCritere, codeEtapeACV, nom, null, null, nomOrganisation)).thenReturn(expectedDTO);

        var actualDTO = referentielRestApi.get(nomCritere, codeEtapeACV, nom, null, null, nomOrganisation);
        assertSame(expectedDTO, actualDTO);
        verify(referentielFacade).getByFilters(nomCritere, codeEtapeACV, nom, null, null, nomOrganisation);
    }

    @Test
    void get_whenNotFound_thenShouldThrowReferentielException() throws ReferentielException {
        String nom = "Ordinateur Portable";
        String nomOrganisation = "nomOrga";
        String nomCritere = "Changement Climatique";
        String codeEtapeACV = "UTILISATION";

        when(referentielFacade.getByFilters(nomCritere, codeEtapeACV, nom, null, null, nomOrganisation)).thenThrow(new ReferentielException("Impact Equipement non trouvé"));

        var exception = assertThrows(ReferentielException.class, () -> referentielRestApi.get(nomCritere, codeEtapeACV, nom, null, null, nomOrganisation));
        assertEquals("Impact Equipement non trouvé", exception.getMessage());
    }

    @Test
    void importCSV_shouldCallPurgeByOrganisationAndAddAll() throws IOException, ReferentielException {
        doNothing().when(referentielFacade).purgeByOrganisationAndAddAll(any(), any());
        referentielRestApi.importCSV(new MockMultipartFile("Name", "AAAAAAAA".getBytes(StandardCharsets.UTF_8)), "FULL", "nomOrga");
        verify(referentielFacade).purgeByOrganisationAndAddAll(any(), eq("nomOrga"));
    }

    @Test
    void importCSV_shouldCallUpsert() throws IOException, ReferentielException {
        referentielRestApi.importCSV(new MockMultipartFile("Name", "AAAAAAAA".getBytes(StandardCharsets.UTF_8)), "DELTA", "nomOrga");
        verify(referentielFacade).upsert(any());
    }

    @Test
    void importCSV_withWrongModeShouldThrowException() throws IOException, ReferentielException {
        var exception = assertThrows(ReferentielException.class, () -> referentielRestApi.importCSV(new MockMultipartFile("Name", "AAAAAAAA".getBytes(StandardCharsets.UTF_8)), "WRONG", "nomOrga"));
        assertEquals("Le mode d'import indiqué n'est pas valide", exception.getMessage());

    }

    @Test
    void importCSV_whenEmptyFileThenShouldThrowException() throws ReferentielException {
        doNothing().when(referentielFacade).purgeByOrganisationAndAddAll(any(), any());
        MockMultipartFile file = new MockMultipartFile("Name", (byte[]) null);
        ResponseStatusException responseStatusException = assertThrows(ResponseStatusException.class, () -> referentielRestApi.importCSV(file, "FULL", "nomOrga"));
        assertEquals(HttpStatus.BAD_REQUEST, responseStatusException.getStatusCode());
        assertEquals("Le fichier n'existe pas ou alors il est vide", responseStatusException.getReason());
    }

    @Test
    void importCSV_whenNullFileThenShouldThrowException() throws ReferentielException {
        doNothing().when(referentielFacade).purgeByOrganisationAndAddAll(any(), any());
        ResponseStatusException responseStatusException = assertThrows(ResponseStatusException.class, () -> referentielRestApi.importCSV(null, "FULL", "nomOrga"));
        assertEquals(HttpStatus.BAD_REQUEST, responseStatusException.getStatusCode());
        assertEquals("Le fichier n'existe pas ou alors il est vide", responseStatusException.getReason());
    }

    @Test
    void exportCSV_shouldReturnCSVFile() throws UnsupportedEncodingException {
        var servletResponse = new MockHttpServletResponse();

        assertDoesNotThrow(() -> referentielRestApi.exportCSV(servletResponse));

        assertEquals("text/csv;charset=UTF-8", servletResponse.getContentType());
        String headerContentDisposition = servletResponse.getHeader("Content-Disposition");
        assertNotNull(headerContentDisposition);
        assertTrue(headerContentDisposition.contains("attachment; filename=facteursCaracterisation-"));
        assertEquals(200, servletResponse.getStatus());

    }
}
