package de.effigenix.infrastructure.usermanagement.web;

import de.effigenix.domain.usermanagement.RoleName;
import de.effigenix.infrastructure.AbstractIntegrationTest;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.util.Set;

import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.hasSize;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@DisplayName("Role Controller Integration Tests")
class RoleControllerIntegrationTest extends AbstractIntegrationTest {

    private String adminToken;
    private String viewerToken;

    @BeforeEach
    void setUp() {
        String adminRoleId = createRole(RoleName.ADMIN, "Admin");
        String viewerRoleId = createRole(RoleName.PRODUCTION_WORKER, "Viewer");

        String adminId = createUser("role.admin", "role.admin@test.com", Set.of(adminRoleId), "BRANCH-01");
        String viewerId = createUser("role.viewer", "role.viewer@test.com", Set.of(viewerRoleId), "BRANCH-01");

        adminToken = generateToken(adminId, "role.admin", "ROLE_READ");
        viewerToken = generateToken(viewerId, "role.viewer", "USER_READ");
    }

    @Test
    @DisplayName("Rollen auflisten mit ROLE_READ → 200")
    void listRoles_withPermission_returns200() throws Exception {
        mockMvc.perform(get("/api/roles")
                        .header("Authorization", "Bearer " + adminToken))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$", hasSize(greaterThanOrEqualTo(2))));
    }

    @Test
    @DisplayName("Rollen auflisten ohne ROLE_READ → 403")
    void listRoles_withoutPermission_returns403() throws Exception {
        mockMvc.perform(get("/api/roles")
                        .header("Authorization", "Bearer " + viewerToken))
                .andExpect(status().isForbidden());
    }

    @Test
    @DisplayName("Rollen auflisten ohne Token → 401")
    void listRoles_withoutToken_returns401() throws Exception {
        mockMvc.perform(get("/api/roles"))
                .andExpect(status().isUnauthorized());
    }
}
