/*
 * 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.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
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.ModuleControllerApi;
import nl.tudelft.labracore.api.dto.*;

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.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.WithUserDetails;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;

import reactor.core.publisher.Mono;
import test.TestDatabaseLoader;
import test.labracore.EditionApiMocker;
import test.labracore.ModuleApiMocker;
import test.labracore.RoleApiMocker;
import test.test.TestQueueApplication;

@Transactional
@AutoConfigureMockMvc
@SpringBootTest(classes = TestQueueApplication.class)
public class ModuleControllerTest {

	@Autowired
	private MockMvc mvc;

	@Autowired
	private ModuleControllerApi mApi;

	@Autowired
	private EditionApiMocker eApiMocker;

	@Autowired
	private ModuleApiMocker mApiMocker;

	@Autowired
	private RoleApiMocker rApiMocker;

	@Autowired
	private TestDatabaseLoader db;

	private EditionDetailsDTO edition1;
	private ModuleDetailsDTO module1;

	@BeforeEach
	void setUp() {
		eApiMocker.mock();
		mApiMocker.mock();
		rApiMocker.mock();

		edition1 = db.getOopNow();
		module1 = db.getOopNowLabsModule();
	}

	@Test
	@WithUserDetails("admin")
	void getModuleCreatePageLoads() throws Exception {
		mvc.perform(get("/edition/{id}/modules/create", edition1.getId()))
				.andExpect(status().isOk())
				.andExpect(view().name("module/create"))
				.andExpect(model().attributeExists("dto", "edition"));
	}

	@Test
	@WithUserDetails("admin")
	void createModuleCreatesANewModule() throws Exception {
		when(mApi.addModule(any())).thenReturn(Mono.just(787832L));

		mvc.perform(post("/edition/{id}/modules/create", edition1.getId()).with(csrf())
				.queryParam("editionId", "" + edition1.getId())
				.queryParam("name", "Cool Module"))
				.andExpect(redirectedUrl("/edition/" + edition1.getId() + "/modules"));

		verify(mApi).addModule(eq(new ModuleCreateDTO()
				.name("Cool Module")
				.edition(new EditionIdDTO().id(edition1.getId()))));
	}

	@Test
	@WithUserDetails("admin")
	void getModuleRemovePageWorks() throws Exception {
		mvc.perform(get("/module/{moduleId}/remove", module1.getId()))
				.andExpect(status().isOk())
				.andExpect(view().name("module/remove"))
				.andExpect(model().attributeExists("edition", "_module"));
	}

	@Test
	@WithUserDetails("admin")
	void removeModuleRedirectsBackToModulesOverview() throws Exception {
		when(mApi.deleteModule(module1.getId())).thenReturn(Mono.empty());

		mvc.perform(post("/module/{moduleId}/remove", module1.getId()).with(csrf()))
				.andExpect(redirectedUrl("/edition/" + edition1.getId() + "/modules"));
	}

	@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("/edition/{editionId}/modules/create", 1),
				post("/edition/{editionId}/modules/create", 1),
				get("/module/{moduleId}/remove", 1),
				post("/module/{moduleId}/remove", 1));
	}
}
