package cz.muni.fi.pa165.core.house;

import com.fasterxml.jackson.databind.ObjectMapper;
import cz.muni.fi.pa165.model.dto.house.HouseCreateDto;
import cz.muni.fi.pa165.model.dto.house.HouseDto;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.web.servlet.MockMvc;

import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@SpringBootTest
@WithMockUser
@AutoConfigureMockMvc(addFilters = false)
@TestPropertySource(locations = "classpath:application-test.properties")
public class HouseControllerTest {

    @Autowired
    private MockMvc mockMvc;
    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private HouseFacade houseFacade;

    @Autowired
    private HouseService houseService;

    private final static String URL = "/api/house";
    private final static String CONTENT_TYPE =  "application/json";

    @BeforeEach
    void setUp() {
        HouseCreateDto h1 = new HouseCreateDto();
        h1.setCity("Sarajevo");
        h1.setAddress("Titova 9");
        houseFacade.create(h1);

        HouseCreateDto h2 = new HouseCreateDto();
        h2.setCity("Brno");
        h2.setAddress("Chrvatska 2");
        houseFacade.create(h2);
    }

    @Test
    void createHouseTest() throws Exception {
        HouseCreateDto h2 = new HouseCreateDto();
        h2.setCity("Brno");
        h2.setAddress("Chrvatska 2");

        String response = mockMvc.perform(post(URL)
                        .contentType(CONTENT_TYPE)
                        .content(objectMapper.writeValueAsString(h2)))
                .andExpect(status().isOk())
                .andReturn()
                .getResponse()
                .getContentAsString();

        HouseDto houseDto = objectMapper.readValue(response, HouseDto.class);
        assertThat(houseDto.getId()).isNotNull();
        assertThat(houseDto.getAddress()).isEqualTo(houseDto.getAddress());
    }
}
