package org.mte.numecoeval.referentiel.infrastructure.adapter.export;

import org.apache.commons.csv.CSVPrinter;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mte.numecoeval.referentiel.domain.ports.input.impl.ImportImpactEquipementPortImpl;
import org.mte.numecoeval.referentiel.factory.TestDataFactory;
import org.mte.numecoeval.referentiel.infrastructure.jpa.repository.ImpactEquipementRepository;

import java.io.IOException;
import java.io.StringWriter;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.List;
import java.util.Locale;

import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.when;

class ImpactEquipementCsvExportServiceTest {

    @InjectMocks
    ImpactEquipementCsvExportService exportService;

    @Mock
    ImpactEquipementRepository repository;

    @Mock
    CSVPrinter csvPrinter;

    @BeforeEach
    void setup() {
        MockitoAnnotations.openMocks(this);
    }

    @Test
    void getHeadersShouldReturnSameHeadersAsImport() {
        assertEquals(ImportImpactEquipementPortImpl.getHeaders(), exportService.getHeaders());
    }

    @Test
    void getObjectsToWriteShouldReturnRepositoryFindAll() {
        var entities = List.of(
                TestDataFactory.ImpactEquipementFactory.entity(
                        TestDataFactory.EtapeFactory.entity("UTILISATION", ""),
                        TestDataFactory.CritereFactory.entity("Changement climatique", "", ""),
                        "Ref-Ecran", "RefTest", "Ecran", 0.1, 0.2
                ),
                TestDataFactory.ImpactEquipementFactory.entity(
                        TestDataFactory.EtapeFactory.entity("DISTRIBUTION", ""),
                        TestDataFactory.CritereFactory.entity("Changement climatique", "", ""),
                        "Ref-Ecran", "RefTest", "Ecran", 0.01, 0.002
                )
        );
        when(repository.findAll()).thenReturn(entities);

        assertEquals(entities, exportService.getObjectsToWrite());
    }

    @Test
    void printRecordShouldUseEntityAttributes() throws IOException {
        var entity = TestDataFactory.ImpactEquipementFactory.entity(
                TestDataFactory.EtapeFactory.entity("UTILISATION", ""),
                TestDataFactory.CritereFactory.entity("Changement climatique", "", ""),
                "Ref-Ecran", "RefTest", "Ecran", 0.1, 0.2
        );
        DecimalFormat df = new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
        df.setMaximumFractionDigits(340);

        assertDoesNotThrow(() -> exportService.printRecord(csvPrinter, entity));

        Mockito.verify(csvPrinter, times(1)).printRecord(entity.getRefEquipement(),
                entity.getEtape(), entity.getCritere(),
                df.format(entity.getConsoElecMoyenne()), df.format(entity.getValeur()),
                entity.getSource(), entity.getType());
    }

    @Test
    void logRecordErrorShouldLogSpecificErrorForRecord() {
        var entity = TestDataFactory.ImpactEquipementFactory.entity(
                TestDataFactory.EtapeFactory.entity("UTILISATION", ""),
                TestDataFactory.CritereFactory.entity("Changement climatique", "", ""),
                "Ref-Ecran", "RefTest", "Ecran", 0.1, 0.2
        );

        assertDoesNotThrow(() -> exportService.logRecordError(entity, new Exception("Test")));
    }

    @Test
    void logRecordErrorShouldLogGenericErrorForRecord() {
        assertDoesNotThrow(() -> exportService.logRecordError(null, new Exception("Test")));
    }

    @Test
    void logRecordErrorShouldLogGenericErrorForFile() {
        assertDoesNotThrow(() -> exportService.logWriterError(new Exception("Test")));
    }

    @Test
    void writeToCsvShouldReturnCSV() {
        // given
        var entities = List.of(
                TestDataFactory.ImpactEquipementFactory.entity(
                        TestDataFactory.EtapeFactory.entity("UTILISATION", ""),
                        TestDataFactory.CritereFactory.entity("Changement climatique", "", ""),
                        "Ref-Ecran", "RefTest", "Ecran", 0.1, 0.2
                )
        );
        when(repository.findAll()).thenReturn(entities);
        StringWriter stringWriter = new StringWriter();

        // when
        exportService.writeToCsv(stringWriter);

        // Then
        String result = stringWriter.toString();
        assertEquals(
                "refEquipement;etapeacv;critere;consoElecMoyenne;valeur;source;type\r\nRef-Ecran;UTILISATION;Changement climatique;0.2;0.1;RefTest;Ecran\r\n",
                result
        );
    }
}
