package net.siegeln.cameleer.saas.vendor;

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.security.core.authority.SimpleGrantedAuthority;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.jwt;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
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 VendorTenantControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private ObjectMapper objectMapper;

    private String createTenant(String name, String slug, String tier) throws Exception {
        var request = new CreateTenantRequest(name, slug, tier, null, null);
        var result = mockMvc.perform(post("/api/vendor/tenants")
                        .with(jwt().jwt(j -> j
                                .claim("sub", "test-user")
                                .claim("organization_id", "test-org-id")
                                .claim("scope", "platform:admin"))
                                .authorities(new SimpleGrantedAuthority("SCOPE_platform:admin")))
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(objectMapper.writeValueAsString(request)))
                .andExpect(status().isCreated())
                .andReturn();
        return objectMapper.readTree(result.getResponse().getContentAsString()).get("id").asText();
    }

    @Test
    void listTenants_returnsAllTenants() throws Exception {
        String slug = "list-test-" + System.nanoTime();
        createTenant("List Test Org", slug, "LOW");

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

    @Test
    void createTenant_returns201() throws Exception {
        String slug = "create-test-" + System.nanoTime();
        var request = new CreateTenantRequest("Create Test Org", slug, "MID", null, null);

        mockMvc.perform(post("/api/vendor/tenants")
                        .with(jwt().jwt(j -> j
                                .claim("sub", "test-user")
                                .claim("organization_id", "test-org-id")
                                .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("Create Test Org"))
                .andExpect(jsonPath("$.slug").value(slug))
                .andExpect(jsonPath("$.tier").value("MID"))
                .andExpect(jsonPath("$.id").isNotEmpty());
    }

    @Test
    void createTenant_returns409ForDuplicateSlug() throws Exception {
        String slug = "duplicate-vendor-" + System.nanoTime();
        createTenant("First Org", slug, "LOW");

        var request = new CreateTenantRequest("Second Org", slug, "LOW", null, null);
        mockMvc.perform(post("/api/vendor/tenants")
                        .with(jwt().jwt(j -> j
                                .claim("sub", "test-user")
                                .claim("organization_id", "test-org-id")
                                .claim("scope", "platform:admin"))
                                .authorities(new SimpleGrantedAuthority("SCOPE_platform:admin")))
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(objectMapper.writeValueAsString(request)))
                .andExpect(status().isConflict());
    }

    @Test
    void getTenantDetail_returnsDetailWithServerStatus() throws Exception {
        String slug = "detail-test-" + System.nanoTime();
        String id = createTenant("Detail Test Org", slug, "LOW");

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

    @Test
    void suspendTenant_returnsUpdatedStatus() throws Exception {
        String slug = "suspend-test-" + System.nanoTime();
        String id = createTenant("Suspend Test Org", slug, "LOW");

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

    @Test
    void deleteTenant_returns204() throws Exception {
        String slug = "delete-test-" + System.nanoTime();
        String id = createTenant("Delete Test Org", slug, "LOW");

        mockMvc.perform(delete("/api/vendor/tenants/" + id)
                        .with(jwt().jwt(j -> j
                                .claim("sub", "test-user")
                                .claim("scope", "platform:admin"))
                                .authorities(new SimpleGrantedAuthority("SCOPE_platform:admin"))))
                .andExpect(status().isNoContent());
    }

    @Test
    void createTenant_returns401WithoutAuth() throws Exception {
        var request = new CreateTenantRequest("No Auth Org", "no-auth-vendor-" + System.nanoTime(), "LOW", null, null);

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