package net.siegeln.cameleer.saas.tenant;

import com.fasterxml.jackson.databind.ObjectMapper;
import net.siegeln.cameleer.saas.TestcontainersConfig;
import net.siegeln.cameleer.saas.TestSecurityConfig;
import net.siegeln.cameleer.saas.tenant.dto.CreateTenantRequest;
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.context.annotation.Import;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;

import org.springframework.security.core.authority.SimpleGrantedAuthority;

import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.jwt;
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.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@SpringBootTest
@AutoConfigureMockMvc
@Import({TestcontainersConfig.class, TestSecurityConfig.class})
@ActiveProfiles("test")
class TenantControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private ObjectMapper objectMapper;

    @Test
    void createTenant_returns201() throws Exception {
        var request = new CreateTenantRequest("Test Org", "test-org-" + System.nanoTime(), "LOW", null, null);

        mockMvc.perform(post("/api/tenants")
                        .with(jwt().jwt(j -> j
                                .claim("sub", "test-user")
                                .claim("organization_id", "test-org")
                                .claim("scope", "platform:admin"))
                                .authorities(new SimpleGrantedAuthority("SCOPE_platform:admin")))
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(objectMapper.writeValueAsString(request)))
                .andExpect(status().isCreated())
                .andExpect(jsonPath("$.name").value("Test Org"))
                .andExpect(jsonPath("$.tier").value("LOW"))
                .andExpect(jsonPath("$.status").value("PROVISIONING"));
    }

    @Test
    void createTenant_returns409ForDuplicateSlug() throws Exception {
        String slug = "duplicate-slug-" + System.nanoTime();
        var request = new CreateTenantRequest("First", slug, null, null, null);

        mockMvc.perform(post("/api/tenants")
                        .with(jwt().jwt(j -> j
                                .claim("sub", "test-user")
                                .claim("scope", "platform:admin"))
                                .authorities(new SimpleGrantedAuthority("SCOPE_platform:admin")))
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(objectMapper.writeValueAsString(request)))
                .andExpect(status().isCreated());

        mockMvc.perform(post("/api/tenants")
                        .with(jwt().jwt(j -> j
                                .claim("sub", "test-user")
                                .claim("scope", "platform:admin"))
                                .authorities(new SimpleGrantedAuthority("SCOPE_platform:admin")))
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(objectMapper.writeValueAsString(request)))
                .andExpect(status().isConflict());
    }

    @Test
    void createTenant_returns401WithoutToken() throws Exception {
        var request = new CreateTenantRequest("Test", "no-auth-test", null, null, null);

        mockMvc.perform(post("/api/tenants")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(objectMapper.writeValueAsString(request)))
                .andExpect(status().isUnauthorized());
    }

    @Test
    void getTenant_returnsTenantById() throws Exception {
        String slug = "get-test-" + System.nanoTime();
        var request = new CreateTenantRequest("Get Test", slug, null, null, null);

        var createResult = mockMvc.perform(post("/api/tenants")
                        .with(jwt().jwt(j -> j
                                .claim("sub", "test-user")
                                .claim("scope", "platform:admin"))
                                .authorities(new SimpleGrantedAuthority("SCOPE_platform:admin")))
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(objectMapper.writeValueAsString(request)))
                .andExpect(status().isCreated())
                .andReturn();

        String id = objectMapper.readTree(createResult.getResponse().getContentAsString()).get("id").asText();

        mockMvc.perform(get("/api/tenants/" + id)
                        .with(jwt().jwt(j -> j.claim("sub", "test-user"))
                                .authorities(new SimpleGrantedAuthority("SCOPE_platform:admin"))))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.slug").value(slug));
    }
}
