package org.mte.numecoeval.referentiel;

import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mte.numecoeval.referentiel.infrastructure.restapi.controller.hypothese.ReferentielHypotheseRestApi;
import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.ErrorResponseDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.env.Environment;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.Arrays;
import java.util.Objects;

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


@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@ActiveProfiles(profiles = {"test"})
class ReferentielApplicationTests {

    @Autowired
    Environment environment;

    @BeforeEach
    public void setupRestAssured() {
        RestAssured.baseURI = "http://localhost";
        RestAssured.port = Integer.parseInt(Objects.requireNonNull(environment.getProperty("server.port")));
    }

    @Test
    void contextLoads() {
        Assertions.assertNotNull(ReferentielApplication.class);
    }

    @Test
    void getHypothese_whenNoData_shouldReturn404() throws NoSuchMethodException {
        String requestPath = Arrays.stream(ReferentielHypotheseRestApi.class.getMethod("get", String.class)
                .getAnnotation(GetMapping.class).path()).findFirst().orElse(null);
        var response = given()
                .contentType(ContentType.JSON)
                .param("cle", "NonExistant")
                .get(requestPath)
                .thenReturn();

        assertEquals(404, response.getStatusCode());
        var errorResponseDTO = response.as(ErrorResponseDTO.class);
        assertEquals(404, errorResponseDTO.getCode());
        assertEquals("Hypothèse non trouvé", errorResponseDTO.getMessage());
    }

    @Test
    void unknownEndpoint_shouldReturn500() throws NoSuchMethodException {
        var response = given()
                .contentType(ContentType.JSON)
                .get("/this/is/not/an/existing/endpoint?true=yes")
                .thenReturn();

        assertEquals(500, response.getStatusCode());
    }
}
