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.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")
                .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[0].code").value("a1"));
    }

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

        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))
            .andExpect(jsonPath("$.data.share").value(10));

        ArgumentCaptor<OffsetDateTime> startCaptor = ArgumentCaptor.forClass(OffsetDateTime.class);
        ArgumentCaptor<OffsetDateTime> endCaptor = ArgumentCaptor.forClass(OffsetDateTime.class);
        verify(trackingService).getConversionFunnel(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 getShareMeta_shouldReturnData() throws Exception {
        when(shareConfigService.getShareMeta(1L, 2L, "default"))
            .thenReturn(Map.of("title", "分享标题"));

        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))
            .andExpect(jsonPath("$.data.title").value("分享标题"));
    }

    @Test
    void registerShareSource_shouldForwardChannelAndParams() throws Exception {
        mockMvc.perform(post("/api/v1/share/register-source")
                .param("activityId", "1")
                .param("userId", "2")
                .param("channel", "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));

        ArgumentCaptor<Map<String, String>> paramsCaptor = ArgumentCaptor.forClass(Map.class);
        verify(trackingService).createShareTracking(eq(1L), eq(2L), eq("wechat"), paramsCaptor.capture());
        Map<String, String> params = paramsCaptor.getValue();
        assertNotNull(params.get("registered_at"));
        assertTrue(params.containsKey("channel"));
        assertTrue(params.containsKey("utm"));
    }
}
