package cz.muni.fi.pa165.statistics.statistics;

import com.fasterxml.jackson.databind.ObjectMapper;
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.test.context.TestPropertySource;
import org.springframework.test.web.servlet.MockMvc;

import java.util.ArrayList;
import java.util.List;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;

@SpringBootTest
@AutoConfigureMockMvc
@TestPropertySource(locations = "classpath:application-test.properties")
public class UserStatisticsControllerTest {

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

	@Autowired
	private StatisticService statisticService;

	private final static String URL = "/api/user-statistics";
	private final static String CONTENT_TYPE = "application/json";

	@Test
	void findAllByUserTest() throws Exception {
		StatisticCreateDto statisticCreateDto = StatisticCreateDto.builder().build();
		statisticCreateDto.setMonthNum(3);
		List<UserStatisticsDto> l = new ArrayList<>();
		assertEquals(statisticService.findAllUserStatistics(statisticCreateDto.getUserId()), l);

		String response = mockMvc.perform(get(URL + "/all?userId=" + statisticCreateDto.getUserId())
						.contentType(CONTENT_TYPE)
						.content(objectMapper.writeValueAsString(statisticCreateDto)))
				.andReturn()
				.getResponse()
				.getContentAsString();
	}

	@Test
	void findHouseStatisticsByUserTest() throws Exception {
		StatisticCreateDto statisticCreateDto = StatisticCreateDto.builder().build();
		statisticCreateDto.setMonthNum(3);
		List<UserStatisticsDto> l = new ArrayList<>();
		assertEquals(statisticService.findAllUserStatisticsByHouse(statisticCreateDto.getUserId(), statisticCreateDto.getHouseId()), l);

		String response = mockMvc.perform(get(URL + "/user?userId=" + statisticCreateDto.getUserId()
						+ "&houseId=" + statisticCreateDto.getHouseId())
						.contentType(CONTENT_TYPE)
						.content(objectMapper.writeValueAsString(statisticCreateDto)))
				.andReturn()
				.getResponse()
				.getContentAsString();
	}

	@Test
	void createStatisticsTest() throws Exception {
		StatisticCreateDto statisticCreateDto = StatisticCreateDto.builder().build();
		statisticCreateDto.setMonthNum(3);
		String jsonBody = objectMapper.writeValueAsString(statisticCreateDto);
		String response = mockMvc.perform(post(URL)
						.contentType(CONTENT_TYPE)
						.content(jsonBody))
				.andReturn()
				.getResponse()
				.getContentAsString();
	}
}
