package com.mosquito.project.integration;

import com.mosquito.project.persistence.entity.ShortLinkEntity;
import com.mosquito.project.persistence.repository.LinkClickRepository;
import com.mosquito.project.persistence.repository.ShortLinkRepository;
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.test.context.TestPropertySource;
import org.springframework.test.web.servlet.MockMvc;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@SpringBootTest
@AutoConfigureMockMvc
@TestPropertySource(properties = {
    "spring.flyway.enabled=false",
    "spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration"
})
class ShortLinkRedirectIntegrationTest {

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private ShortLinkRepository shortLinkRepository;

    @Autowired
    private LinkClickRepository linkClickRepository;

    @Test
    void redirect_shouldLogClick() throws Exception {
        ShortLinkEntity e = new ShortLinkEntity();
        e.setCode("zzTest01");
        e.setOriginalUrl("https://example.com/landing?activityId=99&inviter=42");
        e.setActivityId(99L);
        e.setInviterUserId(42L);
        e.setCreatedAt(java.time.OffsetDateTime.now(java.time.ZoneOffset.UTC));
        shortLinkRepository.save(e);

        mockMvc.perform(get("/r/zzTest01").header("User-Agent", "JUnitTest/1.0"))
            .andExpect(status().isFound())
            .andExpect(header().string("Location", e.getOriginalUrl()));

        var clicks = linkClickRepository.findAll();
        assertThat(clicks).isNotEmpty();
        var c = clicks.get(0);
        assertThat(c.getCode()).isEqualTo("zzTest01");
        assertThat(c.getActivityId()).isEqualTo(99L);
        assertThat(c.getInviterUserId()).isEqualTo(42L);
        assertThat(c.getUserAgent()).contains("JUnitTest");
    }
}

