package com.mosquito.project.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mosquito.project.dto.CreateApiKeyRequest;
import com.mosquito.project.dto.UseApiKeyRequest;
import com.mosquito.project.service.ActivityService;
import com.mosquito.project.support.TestAuthSupport;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.http.MediaType;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.web.servlet.MockMvc;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
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;

@WebMvcTest(ApiKeyController.class)
@Import(com.mosquito.project.config.ControllerTestConfig.class)
@TestPropertySource(properties = {
    "spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration," +
    "org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration," +
    "org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration"
})
class ApiKeyControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private ObjectMapper objectMapper;

    @MockBean
    private ActivityService activityService;

    @Test
    void createApiKey_shouldReturn201WithEnvelope() throws Exception {
        when(activityService.generateApiKey(any(CreateApiKeyRequest.class))).thenReturn("raw-key");
        CreateApiKeyRequest request = new CreateApiKeyRequest();
        request.setActivityId(1L);
        request.setName("test");

        mockMvc.perform(post("/api/v1/api-keys")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(request))
                .header("X-API-Key", TestAuthSupport.RAW_API_KEY)
                .header("Authorization", "Bearer test-token"))
            .andExpect(status().isCreated())
            .andExpect(jsonPath("$.code").value(201))
            .andExpect(jsonPath("$.data.apiKey").value("raw-key"));
    }

    @Test
    void revealApiKey_shouldReturnMessage() throws Exception {
        when(activityService.revealApiKey(1L)).thenReturn("raw-key");

        mockMvc.perform(get("/api/v1/api-keys/1/reveal")
                .header("X-API-Key", TestAuthSupport.RAW_API_KEY)
                .header("Authorization", "Bearer test-token"))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.code").value(200))
            .andExpect(jsonPath("$.data.apiKey").value("raw-key"));
    }

    @Test
    void revokeApiKey_shouldReturnOk() throws Exception {
        mockMvc.perform(delete("/api/v1/api-keys/1")
                .header("X-API-Key", TestAuthSupport.RAW_API_KEY)
                .header("Authorization", "Bearer test-token"))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.code").value(200));

        verify(activityService).revokeApiKey(1L);
    }

    @Test
    void useApiKey_shouldReturnOk() throws Exception {
        UseApiKeyRequest request = new UseApiKeyRequest();
        request.setApiKey("raw-key");

        mockMvc.perform(post("/api/v1/api-keys/1/use")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(request))
                .header("X-API-Key", TestAuthSupport.RAW_API_KEY)
                .header("Authorization", "Bearer test-token"))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.code").value(200));

        verify(activityService).validateAndMarkApiKeyUsed(1L, "raw-key");
    }

    @Test
    void validateApiKey_shouldReturnOk() throws Exception {
        UseApiKeyRequest request = new UseApiKeyRequest();
        request.setApiKey("raw-key");

        mockMvc.perform(post("/api/v1/api-keys/validate")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(request))
                .header("X-API-Key", TestAuthSupport.RAW_API_KEY)
                .header("Authorization", "Bearer test-token"))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.code").value(200));

        verify(activityService).validateApiKeyByPrefixAndMarkUsed("raw-key");
    }
}
