package org.mte.numecoeval.referentiel.steps;

import io.restassured.RestAssured;
import io.restassured.response.Response;
import org.mte.numecoeval.referentiel.infrastructure.restapi.controller.critere.ReferentielAdministrationCritereRestApi;
import org.mte.numecoeval.referentiel.infrastructure.restapi.controller.etape.ReferentielAdministrationEtapeRestApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Objects;

import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;

@Transactional
public abstract class AbstractStepDefinitions {

    @Autowired
    protected Environment environment;

    protected Response response;

    /**
     * Configuration par défaut pour les clients d'API
     */
    protected void setupRestAssured() {
        RestAssured.baseURI = "http://localhost";
        RestAssured.port = Integer.parseInt(Objects.requireNonNull(environment.getProperty("server.port")));
    }

    /**
     * Initialisation des référentiels étapes et critères avec des valeurs par défaut.
     * @throws FileNotFoundException
     * @throws NoSuchMethodException
     */
    protected void initAlimentationEtapeEtCritere() throws FileNotFoundException, NoSuchMethodException {
        RestAssured.baseURI = "http://localhost";
        RestAssured.port = Integer.parseInt(Objects.requireNonNull(environment.getProperty("server.port")));
        File fileCritere = ResourceUtils.getFile("classpath:" + "csv/ref_Critere.csv");
        File fileEtape = ResourceUtils.getFile("classpath:" + "csv/ref_etapeACV.csv");
        //chargement Etape
        String path = Arrays.stream(ReferentielAdministrationCritereRestApi.class.getMethod("importCSV", MultipartFile.class)
                .getAnnotation(PostMapping.class).path()).findFirst().orElse(null);
        Response response = given()
                .multiPart("file", fileCritere)
                .post(path)
                .thenReturn();
        assertEquals(200, response.getStatusCode());

        path = Arrays.stream(ReferentielAdministrationEtapeRestApi.class.getMethod("importCSV", MultipartFile.class)
                .getAnnotation(PostMapping.class).path()).findFirst().orElse(null);
        response = given()
                .multiPart("file", fileEtape)
                .post(path)
                .thenReturn();
        assertEquals(200, response.getStatusCode());
    }
}
