package com.mosquito.project.controller;

import com.mosquito.project.dto.ShareMetricsResponse;
import com.mosquito.project.dto.ShareTrackingResponse;
import com.mosquito.project.service.ShareConfigService;
import com.mosquito.project.service.ShareTrackingService;
import com.mosquito.project.support.TestAuthSupport;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
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 java.time.OffsetDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
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(ShareTrackingController.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 ShareTrackingControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private ShareTrackingService trackingService;

    @MockBean
    private ShareConfigService shareConfigService;

    @Test
    void createShareTracking_shouldReturnPayload() throws Exception {
        ShareTrackingResponse response = new ShareTrackingResponse("track-1", "abc123", "https://example.com", 1L, 2L);
        when(trackingService.createShareTracking(eq(1L), eq(2L), eq("wechat"), any())).thenReturn(response);

        mockMvc.perform(post("/api/v1/share/track")
                .param("activityId", "1")
                .param("inviterUserId", "2")
                .param("source", "wechat")
                .param("utm", "campaign-a")
                .accept(MediaType.APPLICATION_JSON)
                .header("X-API-Key", TestAuthSupport.RAW_API_KEY)
                .header("Authorization", "Bearer test-token"))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.code").value(200))
            .andExpect(jsonPath("$.data.shortCode").value("abc123"));
    }

    @Test
    void getShareMetrics_shouldApplyDefaultTimeRange() throws Exception {
        ShareMetricsResponse metrics = new ShareMetricsResponse();
        metrics.setActivityId(1L);
        when(trackingService.getShareMetrics(eq(1L), any(), any())).thenReturn(metrics);

        mockMvc.perform(get("/api/v1/share/metrics")
                .param("activityId", "1")
                .accept(MediaType.APPLICATION_JSON)
                .header("X-API-Key", TestAuthSupport.RAW_API_KEY)
                .header("Authorization", "Bearer test-token"))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.code").value(200));

        ArgumentCaptor<OffsetDateTime> startCaptor = ArgumentCaptor.forClass(OffsetDateTime.class);
        ArgumentCaptor<OffsetDateTime> endCaptor = ArgumentCaptor.forClass(OffsetDateTime.class);
        verify(trackingService).getShareMetrics(eq(1L), startCaptor.capture(), endCaptor.capture());

        OffsetDateTime start = startCaptor.getValue();
        OffsetDateTime end = endCaptor.getValue();
        assertNotNull(start);
        assertNotNull(end);
        long days = ChronoUnit.DAYS.between(start, end);
        assertTrue(days >= 6 && days <= 8);
    }

    @Test
    void getTopShareLinks_shouldReturnList() throws Exception {
        when(trackingService.getTopShareLinks(1L, 10)).thenReturn(List.of(Map.of("code", "a1")));

        mockMvc.perform(get("/api/v1/share/top-links")
                .param("activityId", "1")
                .param("topN", "10")
                .accept(MediaType.APPLICATION_JSON)
                .header("X-API-Key", TestAuthSupport.RAW_API_KEY)
                .header("Authorization", "Bearer test-token"))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    void getConversionFunnel_shouldApplyDefaultTimeRange() throws Exception {
        when(trackingService.getConversionFunnel(eq(1L), any(), any())).thenReturn(Map.of("shares", 100));

        mockMvc.perform(get("/api/v1/share/funnel")
                .param("activityId", "1")
                .accept(MediaType.APPLICATION_JSON)
                .header("X-API-Key", TestAuthSupport.RAW_API_KEY)
                .header("Authorization", "Bearer test-token"))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    void getConversionFunnel_shouldUseProvidedTimeRange() throws Exception {
        OffsetDateTime start = OffsetDateTime.now().minusDays(30);
        OffsetDateTime end = OffsetDateTime.now();

        when(trackingService.getConversionFunnel(eq(1L), any(), any())).thenReturn(Map.of("shares", 100));

        mockMvc.perform(get("/api/v1/share/funnel")
                .param("activityId", "1")
                .param("startTime", start.toString())
                .param("endTime", end.toString())
                .accept(MediaType.APPLICATION_JSON)
                .header("X-API-Key", TestAuthSupport.RAW_API_KEY)
                .header("Authorization", "Bearer test-token"))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.code").value(200));

        verify(trackingService).getConversionFunnel(eq(1L), any(), any());
    }

    @Test
    void getShareMeta_shouldReturnMetadata() throws Exception {
        Map<String, Object> meta = Map.of("title", "Test Activity", "description", "Test Description");
        when(shareConfigService.getShareMeta(1L, 2L, "default")).thenReturn(meta);

        mockMvc.perform(get("/api/v1/share/share-meta")
                .param("activityId", "1")
                .param("userId", "2")
                .param("template", "default")
                .accept(MediaType.APPLICATION_JSON)
                .header("X-API-Key", TestAuthSupport.RAW_API_KEY)
                .header("Authorization", "Bearer test-token"))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.code").value(200))
            .andExpect(jsonPath("$.data.title").value("Test Activity"));
    }

    @Test
    void getShareMeta_shouldUseDefaultTemplate() throws Exception {
        Map<String, Object> meta = Map.of("title", "Test");
        when(shareConfigService.getShareMeta(1L, 2L, "default")).thenReturn(meta);

        mockMvc.perform(get("/api/v1/share/share-meta")
                .param("activityId", "1")
                .param("userId", "2")
                .accept(MediaType.APPLICATION_JSON)
                .header("X-API-Key", TestAuthSupport.RAW_API_KEY)
                .header("Authorization", "Bearer test-token"))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.code").value(200));

        verify(shareConfigService).getShareMeta(1L, 2L, "default");
    }

    @Test
    void registerShareSource_shouldCreateTracking() throws Exception {
        ShareTrackingResponse response = new ShareTrackingResponse("track-2", "xyz789", "https://example.com", 1L, 3L);
        when(trackingService.createShareTracking(eq(1L), eq(3L), eq("wechat"), any())).thenReturn(response);

        mockMvc.perform(post("/api/v1/share/register-source")
                .param("activityId", "1")
                .param("userId", "3")
                .param("channel", "wechat")
                .accept(MediaType.APPLICATION_JSON)
                .header("X-API-Key", TestAuthSupport.RAW_API_KEY)
                .header("Authorization", "Bearer test-token"))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.code").value(200));

        ArgumentCaptor<Map<String, String>> paramsCaptor = ArgumentCaptor.forClass(Map.class);
        verify(trackingService).createShareTracking(eq(1L), eq(3L), eq("wechat"), paramsCaptor.capture());

        Map<String, String> capturedParams = paramsCaptor.getValue();
        assertThat(capturedParams).containsKey("channel");
        assertThat(capturedParams).containsKey("registered_at");
    }

    @Test
    void registerShareSource_shouldMergeExtraParams() throws Exception {
        ShareTrackingResponse response = new ShareTrackingResponse("track-3", "abc456", "https://example.com", 1L, 4L);
        when(trackingService.createShareTracking(eq(1L), eq(4L), eq("weibo"), any())).thenReturn(response);

        mockMvc.perform(post("/api/v1/share/register-source")
                .param("activityId", "1")
                .param("userId", "4")
                .param("channel", "weibo")
                .param("params", "utm_source=campaign1")
                .accept(MediaType.APPLICATION_JSON)
                .header("X-API-Key", TestAuthSupport.RAW_API_KEY)
                .header("Authorization", "Bearer test-token"))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    void createShareTracking_shouldHandleNullParams() throws Exception {
        ShareTrackingResponse response = new ShareTrackingResponse("track-4", "def123", "https://example.com", 1L, 5L);
        when(trackingService.createShareTracking(eq(1L), eq(5L), eq("direct"), any())).thenReturn(response);

        mockMvc.perform(post("/api/v1/share/track")
                .param("activityId", "1")
                .param("inviterUserId", "5")
                .accept(MediaType.APPLICATION_JSON)
                .header("X-API-Key", TestAuthSupport.RAW_API_KEY)
                .header("Authorization", "Bearer test-token"))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    void getShareMetrics_shouldUseProvidedTimeRange() throws Exception {
        OffsetDateTime start = OffsetDateTime.now().minusDays(30);
        OffsetDateTime end = OffsetDateTime.now();
        ShareMetricsResponse metrics = new ShareMetricsResponse();
        metrics.setActivityId(1L);
        when(trackingService.getShareMetrics(eq(1L), any(), any())).thenReturn(metrics);

        mockMvc.perform(get("/api/v1/share/metrics")
                .param("activityId", "1")
                .param("startTime", start.toString())
                .param("endTime", end.toString())
                .accept(MediaType.APPLICATION_JSON)
                .header("X-API-Key", TestAuthSupport.RAW_API_KEY)
                .header("Authorization", "Bearer test-token"))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.code").value(200));

        verify(trackingService).getShareMetrics(eq(1L), any(), any());
    }

    @Test
    void registerShareSource_shouldHandleNullParams() throws Exception {
        ShareTrackingResponse response = new ShareTrackingResponse("track-5", "ghi789", "https://example.com", 1L, 6L);
        when(trackingService.createShareTracking(eq(1L), eq(6L), eq("email"), any())).thenReturn(response);

        mockMvc.perform(post("/api/v1/share/register-source")
                .param("activityId", "1")
                .param("userId", "6")
                .param("channel", "email")
                .accept(MediaType.APPLICATION_JSON)
                .header("X-API-Key", TestAuthSupport.RAW_API_KEY)
                .header("Authorization", "Bearer test-token"))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.code").value(200));

        ArgumentCaptor<Map<String, String>> paramsCaptor = ArgumentCaptor.forClass(Map.class);
        verify(trackingService).createShareTracking(eq(1L), eq(6L), eq("email"), paramsCaptor.capture());

        Map<String, String> capturedParams = paramsCaptor.getValue();
        assertThat(capturedParams).containsKey("channel");
        assertThat(capturedParams).containsKey("registered_at");
        assertThat(capturedParams.get("channel")).isEqualTo("email");
    }
}
