package com.prudas.app.controller;

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

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.status;

/**
 * Locks in the security boundary at the HTTP layer: public read endpoints
 * must stay open, admin endpoints must reject anonymous callers, and a
 * garbage JWT must not be treated as valid. If someone accidentally
 * loosens SecurityConfig later, this test turns that into a build failure
 * instead of a production incident.
 */
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
class PublicEndpointsSecurityTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    void publicServicesEndpointIsOpen() throws Exception {
        mockMvc.perform(get("/api/services")).andExpect(status().isOk());
    }

    @Test
    void adminEndpointRejectsAnonymousRequest() throws Exception {
        mockMvc.perform(get("/api/admin/services")).andExpect(status().isUnauthorized());
    }

    @Test
    void adminEndpointRejectsGarbageToken() throws Exception {
        mockMvc.perform(get("/api/admin/services").header("Authorization", "Bearer not-a-real-token"))
                .andExpect(status().isUnauthorized());
    }

    @Test
    void contactFormRejectsInvalidPayload() throws Exception {
        mockMvc.perform(post("/api/contact")
                        .contentType("application/json")
                        .content("{\"name\":\"\",\"email\":\"not-an-email\",\"message\":\"\"}"))
                .andExpect(status().isBadRequest());
    }
}
