package enea.lecservice.controllers;

import enea.lecservice.entities.Permission;
import enea.lecservice.models.dto.ServiceResponse;
import enea.lecservice.services.PermissionsService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;

import java.util.Arrays;

import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@ExtendWith(SpringExtension.class)
@WebMvcTest(PermissionsController.class)
class PermissionsControllerTest {

    @Autowired
    MockMvc mvc;

    @MockBean
    PermissionsService permissionsService;

    @Test
    @WithMockUser(username = "testuser", authorities = {"view", "admin"})
    /*@WithAnonymousUser*/
    void list_shouldReturnPermissions() throws Exception {
        when(permissionsService.findAll()).thenReturn(
            ServiceResponse.Success(
                Arrays.asList(
                        Permission.builder().id("view").description("View").build(),
                        Permission.builder().id("admin").description("Admin").build()
                )
            )
        );

        mvc.perform(get("/permissions/admin/list"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.success", is(true)))
                .andExpect(jsonPath("$.result").isArray())
                .andExpect(jsonPath("$.result", hasSize(2)))
        ;
    }
}