/*
 * Queue - A Queueing system that can be used to handle labs in higher education
 * Copyright (C) 2016-2021  Delft University of Technology
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
package nl.tudelft.queue.controller;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

import java.util.List;

import javax.transaction.Transactional;

import nl.tudelft.labracore.api.EditionControllerApi;
import nl.tudelft.labracore.api.ModuleControllerApi;
import nl.tudelft.labracore.api.dto.*;
import nl.tudelft.librador.dto.view.View;
import nl.tudelft.queue.dto.patch.FeedbackPatchDTO;
import nl.tudelft.queue.dto.util.RequestTableFilterDTO;
import nl.tudelft.queue.dto.view.requests.LabRequestViewDTO;
import nl.tudelft.queue.model.LabRequest;
import nl.tudelft.queue.model.enums.RequestType;
import nl.tudelft.queue.model.labs.Lab;
import nl.tudelft.queue.repository.LabRepository;
import nl.tudelft.queue.repository.LabRequestRepository;
import nl.tudelft.queue.service.*;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.modelmapper.ModelMapper;
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.boot.test.mock.mockito.SpyBean;
import org.springframework.security.test.context.support.WithUserDetails;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.ui.Model;

import reactor.core.publisher.Flux;
import test.TestDatabaseLoader;
import test.test.TestQueueApplication;

@Transactional
@AutoConfigureMockMvc
@SpringBootTest(classes = TestQueueApplication.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
class LabRequestControllerTest {
	private Lab lab;
	private Lab emptyLab;

	private EditionDetailsDTO oopNow;
	private RoomDetailsDTO room;

	private LabRequest pendingRequest;
	private LabRequest takenRequest;
	private LabRequest rejectedRequest;

	private RequestTableFilterDTO filter;

	private PersonSummaryDTO assistant0;
	private PersonSummaryDTO assistant5;
	private PersonSummaryDTO headAssistant0;

	@Autowired
	private MockMvc mvc;

	@SpyBean
	private PermissionService permissionService;

	@SpyBean
	private RequestService service;

	@SpyBean
	private FeedbackService fs;

	@SpyBean
	private LabService labService;

	@SpyBean
	private RequestTableService requestTableService;

	@Autowired
	private LabRepository lr;

	@Autowired
	private LabRequestRepository lrr;

	@Autowired
	private TestDatabaseLoader db;

	@Autowired
	private EditionControllerApi eApi;

	@Autowired
	private ModuleControllerApi mApi;

	@BeforeEach
	void setUp() {
		db.mockAll();

		oopNow = db.getOopNow();

		lab = lr.findById(db.getOopNowRegularLab1().getId()).get();
		emptyLab = lr.findById(db.getOopNowRegularLab3().getId()).get();
		room = db.getRoomCz1();

		pendingRequest = lrr.findById(db.getOopNowRegularLab1Requests()[0].getId()).get();
		takenRequest = lrr.findById(db.getOopNowRegularLab1Requests()[30].getId()).get();
		rejectedRequest = lrr.findById(db.getOopNowRegularLab1Requests()[5].getId()).get();

		assistant0 = db.getOopNowTAs()[0].getPerson();
		assistant5 = db.getOopNowTAs()[5].getPerson();
		headAssistant0 = db.getOopNowHeadTAs()[0].getPerson();

		filter = new RequestTableFilterDTO();
		filter.getRequestTypes().add(RequestType.QUESTION);
	}

	@Test
	@WithUserDetails("student52")
	void getNextRequestForbiddenForStudent() throws Exception {
		mvc.perform(get("/requests/next/{lab}", lab.getId()))
				.andExpect(status().isForbidden());
	}

	@Test
	@WithUserDetails("student205")
	void getNextRequestRedirectsToExistingRequest() throws Exception {
		mvc.perform(get("/requests/next/{lab}", lab.getId()))
				.andExpect(status().is3xxRedirection())
				.andExpect(redirectedUrl("/request/" + takenRequest.getId() + "?page=requests"));

		verify(permissionService).canTakeRequest(lab.getId());
		verify(requestTableService).checkAndStoreFilterDTO(null, "/requests");
		verify(service).takeNextRequest(any(), any(), eq(new RequestTableFilterDTO()));
	}

	@Test
	@WithUserDetails("student215")
	void getNextRequestRedirectsToAllIfNoRequest() throws Exception {
		mvc.perform(get("/requests/next/{lab}", emptyLab.getId()))
				.andExpect(status().is3xxRedirection())
				.andExpect(redirectedUrl("/requests?page=requests"));

		verify(permissionService).canTakeRequest(emptyLab.getId());
		verify(requestTableService).checkAndStoreFilterDTO(null, "/requests");
		verify(service).takeNextRequest(any(), any(), any());
	}

	@Test
	@WithUserDetails("student5")
	void getRequestTableViewDoesNotAllowFullStudents() throws Exception {
		mvc.perform(get("/requests"))
				.andExpect(status().isForbidden());

		verify(permissionService, atLeastOnce()).canViewRequests();
	}

	@Test
	@WithUserDetails("student215")
	void getRequestTableViewAllowsIfCanViewRequests() throws Exception {
		when(eApi.getAllEditionsCurrentlyAssistedBy()).thenReturn(Flux.just(
				new EditionSummaryDTO().id(oopNow.getId())));
		when(mApi.getModuleByEdition(anyLong())).thenReturn(Flux.just(oopNow.getModules().stream()
				.map(m -> new ModuleDetailsDTO()).toList().toArray(new ModuleDetailsDTO[0])));

		mvc.perform(get("/requests"))
				.andExpect(status().isOk())
				.andExpect(model().attribute("page", "requests"))
				.andExpect(model().attribute("filter", new RequestTableFilterDTO()))
				.andExpect(model().attributeExists("assignmentsWithCourseCodes"));

		verify(permissionService, atLeastOnce()).canViewRequests();
		verify(requestTableService).checkAndStoreFilterDTO(null, "/requests");
		verify(requestTableService).addFilterAttributes(any(Model.class), eq(null));
		verify(requestTableService).labRequestCounts(any(), any(), eq(new RequestTableFilterDTO()));
	}

	@Test
	@WithUserDetails("student5")
	void updateRequestInfoVerifiesCanUpdateRequest() throws Exception {
		mvc.perform(post("/request/{request}/update-request-info", pendingRequest.getId()).with(csrf()))
				.andExpect(status().isForbidden());

		verify(permissionService).canUpdateRequest(pendingRequest.getId());
	}

	@Test
	@WithUserDetails("student50")
	void updateRequestInfoAllowsIfCanUpdateRequest() throws Exception {
		mvc.perform(post("/request/{request}/update-request-info", pendingRequest.getId()).with(csrf())
				.param("room", "" + room.getId()))
				.andExpect(status().is3xxRedirection())
				.andExpect(redirectedUrl("/lab/" + lab.getId() + "?page=requests"));

		verify(permissionService).canUpdateRequest(pendingRequest.getId());

		assertThat(pendingRequest.getRoom()).isEqualTo(room.getId());
	}

	@Test
	@WithUserDetails("student5")
	void getRequestViewVerifiesCanViewRequest() throws Exception {
		mvc.perform(get("/request/{request}", pendingRequest.getId()))
				.andExpect(status().isForbidden());

		verify(permissionService).canViewRequest(pendingRequest.getId());
	}

	@Test
	@WithUserDetails("student50")
	void getRequestViewAllowsIfCanViewRequest() throws Exception {
		mvc.perform(get("/request/{request}", pendingRequest.getId()))
				.andExpect(status().isOk())
				.andExpect(view().name("request/view/lab"))
				.andExpect(model().attribute("request",
						View.convert(pendingRequest, LabRequestViewDTO.class)));

		verify(permissionService).canViewRequest(pendingRequest.getId());
		verify(labService).setOrganizationInModel(eq(lab), any(Model.class));
	}

	@Test
	@WithUserDetails("student80")
	void getRequestViewFetchesExistingAssistant() throws Exception {
		mvc.perform(get("/request/{request}", takenRequest.getId()))
				.andExpect(status().isOk())
				.andExpect(view().name("request/view/lab"))
				.andExpect(model().attribute("request",
						View.convert(takenRequest, LabRequestViewDTO.class)))
				.andExpect(model().attribute("assistant",
						new ModelMapper().map(assistant5, PersonDetailsDTO.class)));

		verify(permissionService).canViewRequest(takenRequest.getId());
		verify(labService).setOrganizationInModel(eq(lab), any(Model.class));
	}

	@Test
	@WithUserDetails("student5")
	void getRequestApproveViewVerifiesCanFinishRequest() throws Exception {
		mvc.perform(get("/request/{request}/approve", pendingRequest.getId()))
				.andExpect(status().isForbidden());

		verify(permissionService).canFinishRequest(pendingRequest.getId());
	}

	@Test
	@WithUserDetails("student205")
	void getRequestApproveViewAllowsIfCanFinishRequest() throws Exception {
		mvc.perform(get("/request/{request}/approve", takenRequest.getId()))
				.andExpect(status().isOk())
				.andExpect(view().name("request/approve"))
				.andExpect(model().attribute("request", takenRequest));

		verify(permissionService).canFinishRequest(takenRequest.getId());
	}

	@Test
	@WithUserDetails("student5")
	void approveRequestVerifiesCanFinishRequest() throws Exception {
		mvc.perform(post("/request/{request}/approve", pendingRequest.getId()).with(csrf())
				.param("reasonForAssistant", ""))
				.andExpect(status().isForbidden());

		verify(permissionService).canFinishRequest(pendingRequest.getId());
	}

	@Test
	@WithUserDetails("student205")
	void approveRequestAllowsIfCanFinishRequest() throws Exception {
		String reason = "The answer was, inderdeed, 42.";

		mvc.perform(post("/request/{request}/approve", takenRequest.getId()).with(csrf())
				.param("reasonForAssistant", reason))
				.andExpect(status().is3xxRedirection())
				.andExpect(redirectedUrl("/requests"))
				.andExpect(flash().attribute("message", "Request #" + takenRequest.getId() + " approved"));

		verify(permissionService).canFinishRequest(takenRequest.getId());
		verify(service).approveRequest(takenRequest, assistant5.getId(), reason, null);
	}

	@Test
	@WithUserDetails("student5")
	void getRequestRejectViewVerifiesCanFinishRequest() throws Exception {
		mvc.perform(get("/request/{request}/reject", pendingRequest.getId()))
				.andExpect(status().isForbidden());

		verify(permissionService).canFinishRequest(pendingRequest.getId());
	}

	@Test
	@WithUserDetails("student205")
	void getRequestRejectViewAllowsIfCanFinishRequest() throws Exception {
		mvc.perform(get("/request/{request}/reject", takenRequest.getId()))
				.andExpect(status().isOk())
				.andExpect(view().name("request/reject"))
				.andExpect(model().attributeExists("request"));

		verify(permissionService).canFinishRequest(takenRequest.getId());
	}

	@Test
	@WithUserDetails("student5")
	void rejectRequestVerifiesCanFinishRequest() throws Exception {
		mvc.perform(post("/request/{request}/reject", pendingRequest.getId()).with(csrf())
				.param("reasonForAssistant", "")
				.param("reasonForStudent", ""))
				.andExpect(status().isForbidden());

		verify(permissionService).canFinishRequest(pendingRequest.getId());
	}

	@Test
	@WithUserDetails("student205")
	void rejectRequestAllowsIfCanFinishRequest() throws Exception {
		String reasonForAssistant = "was very bad";
		String reasonForStudent = "needs some more work";

		mvc.perform(post("/request/{request}/reject", takenRequest.getId()).with(csrf())
				.param("reasonForAssistant", reasonForAssistant)
				.param("reasonForStudent", reasonForStudent))
				.andExpect(status().is3xxRedirection())
				.andExpect(redirectedUrl("/requests"))
				.andExpect(flash().attribute("message", "Request #" + takenRequest.getId() + " rejected"));

		verify(permissionService).canFinishRequest(takenRequest.getId());
	}

	@Test
	@WithUserDetails("student5")
	void getRequestForwardViewVerifiesCanFinishRequest() throws Exception {
		mvc.perform(get("/request/{request}/forward", pendingRequest.getId()))
				.andExpect(status().isForbidden());

		verify(permissionService).canFinishRequest(pendingRequest.getId());
	}

	@Test
	@WithUserDetails("teacher0")
	void getRequestForwardViewAllowsIfUserIsTeacher() throws Exception {
		mvc.perform(get("/request/{request}/forward", pendingRequest.getId()))
				.andExpect(status().isOk())
				.andExpect(view().name("request/forward"))
				.andExpect(model().attribute("request", pendingRequest));

		verify(permissionService).canFinishRequest(pendingRequest.getId());
		verify(labService).setOrganizationInModel(eq(lab), any(Model.class));
	}

	@Test
	@WithUserDetails("student5")
	void forwardRequestVerifiesCanFinishRequest() throws Exception {
		mvc.perform(post("/request/{request}/forward", pendingRequest.getId()).with(csrf())
				.param("assistant", String.valueOf(-1L))
				.param("reasonForAssistant", ""))
				.andExpect(status().isForbidden());

		verify(permissionService).canFinishRequest(pendingRequest.getId());
	}

	@Test
	@WithUserDetails("student205")
	void forwardRequestAllowsIfCanFinishRequest() throws Exception {
		String reasonForAssistant = "don't like this kid";

		mvc.perform(post("/request/{request}/forward", takenRequest.getId()).with(csrf())
				.param("assistant", String.valueOf(-1L))
				.param("reasonForAssistant", reasonForAssistant))
				.andExpect(status().is3xxRedirection())
				.andExpect(redirectedUrl("/requests"))
				.andExpect(flash().attribute("message", "Request #" + takenRequest.getId() + " forwarded"));

		verify(service).forwardRequestToAnyone(any(), any(), eq(reasonForAssistant));
		verify(permissionService).canFinishRequest(takenRequest.getId());
	}

	@Test
	@WithUserDetails("student205")
	void forwardRequestRegistersForwardedTo() throws Exception {
		String reasonForAssistant = "don't like this kid";

		mvc.perform(post("/request/{request}/forward", takenRequest.getId()).with(csrf())
				.param("assistant", "" + headAssistant0.getId())
				.param("reasonForAssistant", reasonForAssistant))
				.andExpect(status().is3xxRedirection())
				.andExpect(redirectedUrl("/requests"))
				.andExpect(flash().attribute("message", "Request #" + takenRequest.getId() + " forwarded"));
	}

	@Test
	@WithUserDetails("student5")
	void couldNotFindStudentVerifiesCanFinishRequest() throws Exception {
		mvc.perform(get("/request/{request}/not-found", pendingRequest.getId()))
				.andExpect(status().isForbidden());

		verify(permissionService).canFinishRequest(pendingRequest.getId());
	}

	@Test
	@WithUserDetails("student205")
	void couldNotFindStudentAllowsIfCanFinishRequest() throws Exception {
		mvc.perform(get("/request/{request}/not-found", takenRequest.getId()))
				.andExpect(status().is3xxRedirection())
				.andExpect(redirectedUrl("/requests?page=requests"));

		verify(service).couldNotFindStudent(eq(takenRequest), any());
		verify(permissionService).canFinishRequest(takenRequest.getId());
	}

	@Test
	@WithUserDetails("student55")
	void giveFeedbackCallsServiceMethodAndRedirects() throws Exception {
		mvc.perform(
				post("/request/{request}/feedback/{assistant}", rejectedRequest.getId(), assistant0.getId())
						.with(csrf())
						.queryParam("feedback", "Ikeh")
						.queryParam("rating", "4"))
				.andExpect(redirectedUrl("/request/" + rejectedRequest.getId() + "?page=requests"));

		verify(fs).updateFeedback(any(), eq(assistant0.getId()), eq(new FeedbackPatchDTO("Ikeh", 4)));
	}

	@Test
	@WithUserDetails("admin")
	void giveFeedbackNotAllowedForAdmin() throws Exception {
		mvc.perform(post("/request/{request}/feedback/{assistant}", pendingRequest.getId(), 44L).with(csrf())
				.queryParam("feedback", "Ikeh")
				.queryParam("rating", "4"))
				.andExpect(status().isForbidden());
	}

	@Test
	@WithUserDetails("teacher0")
	void pickRequestIsAllowedForTeachers() throws Exception {
		mvc.perform(get("/request/{request}/pick", pendingRequest.getId()).with(csrf()))
				.andExpect(status().is3xxRedirection())
				.andExpect(redirectedUrlTemplate("/request/{id}?page=requests",
						pendingRequest.getId()));
	}

	@ParameterizedTest
	@MethodSource(value = "protectedEndpoints")
	void testWithoutUserDetailsIsForbidden(MockHttpServletRequestBuilder request) throws Exception {
		mvc.perform(request.with(csrf()))
				.andExpect(status().is3xxRedirection())
				.andExpect(redirectedUrl("http://localhost/login"));
	}

	private static List<MockHttpServletRequestBuilder> protectedEndpoints() {
		return List.of(
				get("/requests/next/1"),
				get("/requests"),
				post("/request/1/update-request-info"),
				get("/request/1"),
				get("/request/1/approve"),
				post("/request/1/approve"),
				get("/request/1/reject"),
				post("/request/1/reject"),
				get("/request/1/not-found"),
				post("/request/1/feedback/1"));
	}

}
