package com.mosquito.project.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mosquito.project.dto.RegisterCallbackRequest;
import com.mosquito.project.dto.CreateActivityRequest;
import com.mosquito.project.persistence.entity.ShortLinkEntity;
import com.mosquito.project.persistence.repository.ShortLinkRepository;
import com.mosquito.project.service.ActivityService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;

import java.time.Duration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@SpringBootTest
@AutoConfigureMockMvc(addFilters = false)
@TestPropertySource(properties = {
    "app.rate-limit.per-minute=2",
    "spring.cache.type=simple",
    "mosquito.callback.allow-localhost=true",
    "mosquito.callback.require.device.fingerprint=false"
})
class CallbackControllerIntegrationTest {

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private ActivityService activityService;

    @Autowired
    private ShortLinkRepository shortLinkRepository;

    @MockBean
    private StringRedisTemplate redisTemplate;

    private final Map<String, AtomicLong> rateLimitCounters = new ConcurrentHashMap<>();

    @BeforeEach
    void setUpRedisTemplateMock() {
        @SuppressWarnings("unchecked")
        ValueOperations<String, String> valueOperations = Mockito.mock(ValueOperations.class);
        rateLimitCounters.clear();

        Mockito.when(redisTemplate.opsForValue()).thenReturn(valueOperations);
        Mockito.when(valueOperations.increment(Mockito.anyString()))
            .thenAnswer(invocation -> {
                String key = invocation.getArgument(0, String.class);
                return rateLimitCounters.computeIfAbsent(key, ignored -> new AtomicLong(0)).incrementAndGet();
            });
        Mockito.when(redisTemplate.expire(Mockito.anyString(), Mockito.any(Duration.class))).thenReturn(Boolean.TRUE);
    }

    private void createTrackingId(String trackingId, Long activityId) {
        ShortLinkEntity e = new ShortLinkEntity();
        e.setTrackingId(trackingId);
        e.setCode("test" + trackingId);
        e.setOriginalUrl("https://example.com/test");
        e.setActivityId(activityId);
        e.setCreatedAt(java.time.OffsetDateTime.now(java.time.ZoneOffset.UTC));
        shortLinkRepository.save(e);
    }

    @Test
    void shouldBeIdempotent_andRateLimited() throws Exception {
        // 先创建活动并获取API Key
        CreateActivityRequest r = new CreateActivityRequest();
        r.setName("cb");
        r.setStartTime(java.time.ZonedDateTime.now());
        r.setEndTime(java.time.ZonedDateTime.now().plusDays(1));
        var act = activityService.createActivity(r);
        com.mosquito.project.dto.CreateApiKeyRequest k = new com.mosquito.project.dto.CreateApiKeyRequest();
        k.setActivityId(act.getId());
        k.setName("k");
        String key = activityService.generateApiKey(k);

        // 创建测试用的tracking_id
        createTrackingId("track-001", act.getId());
        createTrackingId("track-002", act.getId());

        RegisterCallbackRequest req = new RegisterCallbackRequest();
        req.setTrackingId("track-001");
        mockMvc.perform(post("/api/v1/callback/register")
                .header("X-API-Key", key)
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(req)))
            .andExpect(status().isOk());
        // 2nd same tracking id should still be OK (idempotent)
        mockMvc.perform(post("/api/v1/callback/register")
                .header("X-API-Key", key)
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(req)))
            .andExpect(status().isOk());

        // exceed rate limit (limit=2 per minute) with a different tracking id
        RegisterCallbackRequest req2 = new RegisterCallbackRequest();
        req2.setTrackingId("track-002");
        mockMvc.perform(post("/api/v1/callback/register")
                .header("X-API-Key", key)
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(req2)))
            .andExpect(status().isTooManyRequests());
    }
}
