package net.siegeln.cameleer.saas.license;

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 LicenseControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private ObjectMapper objectMapper;

    private String createTenantAndGetId() throws Exception {
        String slug = "license-tenant-" + System.nanoTime();
        var request = new CreateTenantRequest("License Test Org", slug, "MID", null, null);

        var result = 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();

        return objectMapper.readTree(result.getResponse().getContentAsString()).get("id").asText();
    }

    @Test
    void generateLicense_returns201WithToken() throws Exception {
        String tenantId = createTenantAndGetId();

        mockMvc.perform(post("/api/tenants/" + tenantId + "/license")
                        .with(jwt().jwt(j -> j.claim("sub", "test-user"))
                                .authorities(new SimpleGrantedAuthority("SCOPE_billing:manage"),
                                        new SimpleGrantedAuthority("SCOPE_platform:admin"))))
                .andExpect(status().isCreated())
                .andExpect(jsonPath("$.token").isNotEmpty())
                .andExpect(jsonPath("$.tier").value("MID"))
                .andExpect(jsonPath("$.features.correlation").value(true));
    }

    @Test
    void getActiveLicense_returnsLicense() throws Exception {
        String tenantId = createTenantAndGetId();

        mockMvc.perform(post("/api/tenants/" + tenantId + "/license")
                        .with(jwt().jwt(j -> j.claim("sub", "test-user"))
                                .authorities(new SimpleGrantedAuthority("SCOPE_billing:manage"),
                                        new SimpleGrantedAuthority("SCOPE_platform:admin"))))
                .andExpect(status().isCreated());

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

    @Test
    void getActiveLicense_returns404WhenNone() throws Exception {
        String tenantId = createTenantAndGetId();

        mockMvc.perform(get("/api/tenants/" + tenantId + "/license")
                        .with(jwt().jwt(j -> j.claim("sub", "test-user"))
                                .authorities(new SimpleGrantedAuthority("SCOPE_platform:admin"))))
                .andExpect(status().isNotFound());
    }
}
