package com.mosquito.project.controller;

import com.mosquito.project.domain.LeaderboardEntry;
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 java.util.List;

import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;

@WebMvcTest(ActivityController.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 ActivityLeaderboardControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private ActivityService activityService;

    @Test
    void shouldReturnLeaderboard_whenActivityExists() throws Exception {
        when(activityService.getLeaderboard(1L)).thenReturn(
            List.of(
                new LeaderboardEntry(1L, "用户A", 1500),
                new LeaderboardEntry(2L, "用户B", 1200)
            )
        );

        mockMvc.perform(get("/api/v1/activities/1/leaderboard")
                .header("X-API-Key", TestAuthSupport.RAW_API_KEY)
                .header("Authorization", "Bearer test-token"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON))
            .andExpect(jsonPath("$.code").value(200))
            .andExpect(jsonPath("$.data").isArray());
    }

    @Test
    void shouldExportLeaderboardCsv_withAttachmentHeaders() throws Exception {
        String csv = "userId,userName,score\n1,用户A,1500\n2,用户B,1200\n";
        when(activityService.generateLeaderboardCsv(1L)).thenReturn(csv);

        mockMvc.perform(get("/api/v1/activities/1/leaderboard/export")
                .header("X-API-Key", TestAuthSupport.RAW_API_KEY)
                .header("Authorization", "Bearer test-token"))
            .andExpect(status().isOk())
            .andExpect(header().string("Content-Type", "text/csv;charset=UTF-8"))
            .andExpect(header().string("Content-Disposition", "attachment; filename=\"leaderboard_1.csv\""))
            .andExpect(content().string(csv));
    }

    @Test
    void shouldSupportPaginationAndTopN_onLeaderboard() throws Exception {
        when(activityService.getLeaderboard(1L)).thenReturn(
            List.of(
                new LeaderboardEntry(1L, "用户1", 1000),
                new LeaderboardEntry(2L, "用户2", 900),
                new LeaderboardEntry(3L, "用户3", 800),
                new LeaderboardEntry(4L, "用户4", 700),
                new LeaderboardEntry(5L, "用户5", 600)
            )
        );

        mockMvc.perform(get("/api/v1/activities/1/leaderboard")
                .param("topN", "4")
                .param("page", "1")
                .param("size", "2")
                .accept(MediaType.APPLICATION_JSON)
                .header("X-API-Key", TestAuthSupport.RAW_API_KEY)
                .header("Authorization", "Bearer test-token"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON))
            .andExpect(jsonPath("$.meta.pagination.total").value(4))
            .andExpect(jsonPath("$.data[0].userId").value(3))
            .andExpect(jsonPath("$.data[1].userId").value(4));
    }

    @Test
    void shouldApplyTopN_onCsvExport() throws Exception {
        when(activityService.generateLeaderboardCsv(1L, 1)).thenReturn("userId,userName,score\n1,用户1,1000\n");

        mockMvc.perform(get("/api/v1/activities/1/leaderboard/export")
                .param("topN", "1")
                .header("X-API-Key", TestAuthSupport.RAW_API_KEY)
                .header("Authorization", "Bearer test-token"))
            .andExpect(status().isOk())
            .andExpect(content().string("userId,userName,score\n1,用户1,1000\n"));
    }
}
