package com.ruoyi.web.modules.prosperity.controller;

import static org.hamcrest.Matchers.containsString;
import static org.mockito.ArgumentMatchers.any;
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.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.framework.web.exception.GlobalExceptionHandler;
import com.ruoyi.web.modules.prosperity.domain.vo.AchievementAnnualReportVo;
import com.ruoyi.web.modules.prosperity.domain.vo.AchievementAnnualSummaryVo;
import com.ruoyi.web.modules.prosperity.domain.vo.AchievementMonthlyVo;
import com.ruoyi.web.modules.prosperity.domain.vo.AchievementReportYearsVo;
import com.ruoyi.web.modules.prosperity.service.IAchievementReportService;
import com.ruoyi.web.modules.prosperity.support.AchievementReportAggregator;

/**
 * GTFY-NB-API-001～012、019
 */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("共同富裕成果年度报告 HTTP 接口 MockMvc")
class BizCommonProsperityAchievementReportControllerApiTest
{

    @Mock
    private IAchievementReportService achievementReportService;

    @InjectMocks
    private BizCommonProsperityAchievementReportController controller;

    private MockMvc mockMvc;

    @BeforeEach
    void setUp()
    {
        mockMvc = MockMvcBuilders.standaloneSetup(controller)
                .setControllerAdvice(new GlobalExceptionHandler())
                .build();
        loginAsAllPermissions();
    }

    @AfterEach
    void tearDown()
    {
        SecurityContextHolder.clearContext();
        PageHelper.clearPage();
    }

    private static void loginAsAllPermissions()
    {
        SysUser u = new SysUser();
        u.setUserId(1L);
        u.setUserName("tester");
        u.setPassword("x");
        Set<String> perms = new HashSet<>();
        perms.add(Constants.ALL_PERMISSION);
        LoginUser lu = new LoginUser(1L, 100L, u, perms);
        UsernamePasswordAuthenticationToken auth =
                new UsernamePasswordAuthenticationToken(lu, "", lu.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(auth);
    }

    @Test
    @DisplayName("GTFY-NB-API-001 GET 年度报告有数据")
    void api001_reportWithData() throws Exception
    {
        when(achievementReportService.getAnnualReport("2026")).thenReturn(sampleReport(true));
        mockMvc.perform(get("/commonProsperity/achievementReport").param("statYear", "2026"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.hasData").value(true))
                .andExpect(jsonPath("$.data.monthly.length()").value(5))
                .andExpect(jsonPath("$.data.summary.collectiveEconomyIncome").exists());
    }

    @Test
    @DisplayName("GTFY-NB-API-003 GET 全年无数据")
    void api003_reportNoData() throws Exception
    {
        when(achievementReportService.getAnnualReport("2026")).thenReturn(sampleReport(false));
        mockMvc.perform(get("/commonProsperity/achievementReport").param("statYear", "2026"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.hasData").value(false))
                .andExpect(jsonPath("$.data.summary").doesNotExist());
    }

    @Test
    @DisplayName("GTFY-NB-API-005 GET 缺 statYear")
    void api005_missingYear() throws Exception
    {
        when(achievementReportService.getAnnualReport(any()))
                .thenThrow(new ServiceException("统计年份不能为空"));
        mockMvc.perform(get("/commonProsperity/achievementReport"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("GTFY-NB-API-006 GET 非法 statYear")
    void api006_invalidYear() throws Exception
    {
        when(achievementReportService.getAnnualReport("abc"))
                .thenThrow(new ServiceException("统计年份须为4位数字（如2026）"));
        mockMvc.perform(get("/commonProsperity/achievementReport").param("statYear", "abc"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("GTFY-NB-API-007 GET statYear 回显")
    void api007_statYearEcho() throws Exception
    {
        AchievementAnnualReportVo report = sampleReport(true);
        report.setStatYear(2025);
        when(achievementReportService.getAnnualReport("2025")).thenReturn(report);
        mockMvc.perform(get("/commonProsperity/achievementReport").param("statYear", "2025"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.statYear").value(2025));
    }

    @Test
    @DisplayName("GTFY-NB-API-010 GET monthly 字段齐全")
    void api010_monthlyFields() throws Exception
    {
        when(achievementReportService.getAnnualReport("2026")).thenReturn(sampleReport(true));
        mockMvc.perform(get("/commonProsperity/achievementReport").param("statYear", "2026"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.monthly[0].month").exists())
                .andExpect(jsonPath("$.data.monthly[0].employmentDrivenCount").exists())
                .andExpect(jsonPath("$.data.monthly[0].digitalPlatformUsageRate").exists());
    }

    @Test
    @DisplayName("GTFY-NB-API-011 GET /years")
    void api011_years() throws Exception
    {
        AchievementReportYearsVo vo = new AchievementReportYearsVo();
        vo.setYears(Arrays.asList(2026, 2024));
        when(achievementReportService.listAvailableYears()).thenReturn(vo);
        mockMvc.perform(get("/commonProsperity/achievementReport/years"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.years.length()").value(2));
    }

    @Test
    @DisplayName("GTFY-NB-API-012 GET /years 空")
    void api012_yearsEmpty() throws Exception
    {
        AchievementReportYearsVo vo = new AchievementReportYearsVo();
        vo.setYears(Collections.emptyList());
        when(achievementReportService.listAvailableYears()).thenReturn(vo);
        mockMvc.perform(get("/commonProsperity/achievementReport/years"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.years").isEmpty());
    }

    @Test
    @DisplayName("GTFY-NB-API-019 失败可读 msg")
    void api019_errorMsg() throws Exception
    {
        when(achievementReportService.getAnnualReport("26"))
                .thenThrow(new ServiceException("统计年份须为4位数字（如2026）"));
        mockMvc.perform(get("/commonProsperity/achievementReport").param("statYear", "26"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500))
                .andExpect(jsonPath("$.msg").value(containsString("4位")));
    }

    private static AchievementAnnualReportVo sampleReport(boolean hasData)
    {
        if (hasData)
        {
            return AchievementReportAggregator.buildReport(2026,
                    Collections.singletonList(com.ruoyi.web.modules.prosperity.ProsperityAchievementTestSamples.sample()));
        }
        return AchievementReportAggregator.buildReport(2026, Collections.emptyList());
    }
}
