package org.mte.numecoeval.referentiel.steps;

import io.cucumber.java.fr.Alors;
import io.cucumber.java.fr.Quand;
import io.restassured.http.ContentType;
import io.restassured.path.json.JsonPath;
import org.mte.numecoeval.referentiel.infrastructure.restapi.controller.hypothese.ReferentielAdministrationHypotheseRestApi;
import org.mte.numecoeval.referentiel.infrastructure.restapi.controller.hypothese.ReferentielHypotheseRestApi;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
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 static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class HypotheseStepdefs extends AbstractStepDefinitions {

    @Quand("le fichier CSV REF HYPOTHESE{string} est inject")
    public void leFichierCSVREFHYPOTHESEEstInject(String nomFichier) throws FileNotFoundException, NoSuchMethodException {

        setupRestAssured();
        File file = ResourceUtils.getFile("classpath:" + nomFichier);
        String requestPath = Arrays.stream(ReferentielAdministrationHypotheseRestApi.class.getMethod("importCSV", MultipartFile.class)
                .getAnnotation(PostMapping.class).path()).findFirst().orElse(null);
        response = given()
                .multiPart("file", file)
                .post(requestPath)
                .thenReturn();

    }

    @Alors("le statut http est {int}")
    public void checkReponseApi(int codeHttpAttendu) {
        assertEquals(codeHttpAttendu, response.getStatusCode());
    }

    @Quand("lors de la recherche de hypothese avec la cle {string}")
    public void lorsDeLaRechercheDeHypotheseAvecLaCle(String cle) throws NoSuchMethodException {
        setupRestAssured();
        String requestPath = Arrays.stream(ReferentielHypotheseRestApi.class.getMethod("get", String.class)
                .getAnnotation(GetMapping.class).path()).findFirst().orElse(null);
        response = given()
                .contentType(ContentType.JSON)
                .param("cle", cle)
                .get(requestPath)
                .thenReturn();
        assertEquals(200, response.getStatusCode());

    }

    @Alors("Le resultat est : cle = {string} valeur={string} et source={string}")
    public void leResultatEstCleValeurEtSource(String cle, String valeur, String source) {
        JsonPath jsonPath = response.jsonPath();
        assertEquals(cle, jsonPath.get("code"));
        assertEquals(source, jsonPath.get("source"));
        assertEquals(valeur, jsonPath.get("valeur"));


    }
}
