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.delete;
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.request.MockMvcRequestBuilders.put;
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.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.http.MediaType;
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.fasterxml.jackson.databind.ObjectMapper;
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.BizCommonProsperityAchievement;
import com.ruoyi.web.modules.prosperity.service.IBizCommonProsperityAchievementService;
import com.ruoyi.web.modules.prosperity.ProsperityAchievementTestSamples;

/**
 * GTFY-CG-API-001～023（MockMvc + Mock Service）
 */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("共同富裕成果 HTTP 接口 MockMvc")
class BizCommonProsperityAchievementControllerApiTest
{

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Mock
    private IBizCommonProsperityAchievementService bizCommonProsperityAchievementService;

    @InjectMocks
    private BizCommonProsperityAchievementController 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-CG-API-001 GET /list 分页")
    void api001_list() throws Exception
    {
        when(bizCommonProsperityAchievementService.selectBizCommonProsperityAchievementList(any()))
                .thenReturn(Collections.singletonList(sample(1L)));
        mockMvc.perform(get("/commonProsperity/achievement/list").param("pageNum", "1").param("pageSize", "20"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.rows").isArray());
    }

    @Test
    @DisplayName("GTFY-CG-API-002 GET /list statYear")
    void api002_listStatYear() throws Exception
    {
        when(bizCommonProsperityAchievementService.selectBizCommonProsperityAchievementList(any()))
                .thenReturn(Collections.emptyList());
        mockMvc.perform(get("/commonProsperity/achievement/list").param("statYear", "2026"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("GTFY-CG-API-003 GET /list 无 statYear")
    void api003_listNoYear() throws Exception
    {
        when(bizCommonProsperityAchievementService.selectBizCommonProsperityAchievementList(any()))
                .thenReturn(Collections.singletonList(sample(1L)));
        mockMvc.perform(get("/commonProsperity/achievement/list"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("GTFY-CG-API-005 POST 新增成功")
    void api005_add() throws Exception
    {
        when(bizCommonProsperityAchievementService.insertBizCommonProsperityAchievement(any())).thenReturn(1);
        mockMvc.perform(post("/commonProsperity/achievement")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(ProsperityAchievementTestSamples.sample())))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("GTFY-CG-API-006 POST 统计范围重复")
    void api006_addDuplicate() throws Exception
    {
        when(bizCommonProsperityAchievementService.insertBizCommonProsperityAchievement(any()))
                .thenThrow(new ServiceException("该月份成果已存在"));
        mockMvc.perform(post("/commonProsperity/achievement")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(ProsperityAchievementTestSamples.sample())))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500))
                .andExpect(jsonPath("$.msg").value(containsString("月份")));
    }

    @Test
    @DisplayName("GTFY-CG-API-008 POST 比率大于1")
    void api008_addRateOverOne() throws Exception
    {
        when(bizCommonProsperityAchievementService.insertBizCommonProsperityAchievement(any()))
                .thenThrow(new ServiceException("数字平台使用率须在0～1之间"));
        BizCommonProsperityAchievement body = ProsperityAchievementTestSamples.sample();
        body.setDigitalPlatformUsageRate(new BigDecimal("1.2"));
        mockMvc.perform(post("/commonProsperity/achievement")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("GTFY-CG-API-011 POST 收入为负")
    void api011_addNegativeIncome() throws Exception
    {
        when(bizCommonProsperityAchievementService.insertBizCommonProsperityAchievement(any()))
                .thenThrow(new ServiceException("集体经济收入须大于等于0"));
        BizCommonProsperityAchievement body = ProsperityAchievementTestSamples.sample();
        body.setCollectiveEconomyIncome(new BigDecimal("-1"));
        mockMvc.perform(post("/commonProsperity/achievement")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("GTFY-CG-API-013 GET /{id} 详情")
    void api013_getDetail() throws Exception
    {
        when(bizCommonProsperityAchievementService.selectBizCommonProsperityAchievementById(2L))
                .thenReturn(sample(2L));
        mockMvc.perform(get("/commonProsperity/achievement/2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.statPeriod").exists())
                .andExpect(jsonPath("$.data.collectiveEconomyIncome").exists());
    }

    @Test
    @DisplayName("GTFY-CG-API-015 PUT 修改成功")
    void api015_put() throws Exception
    {
        when(bizCommonProsperityAchievementService.updateBizCommonProsperityAchievement(any())).thenReturn(1);
        BizCommonProsperityAchievement body = ProsperityAchievementTestSamples.sample();
        body.setId(8L);
        mockMvc.perform(put("/commonProsperity/achievement")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("GTFY-CG-API-016 PUT 改月冲突")
    void api016_putConflict() throws Exception
    {
        when(bizCommonProsperityAchievementService.updateBizCommonProsperityAchievement(any()))
                .thenThrow(new ServiceException("该月份成果已存在"));
        BizCommonProsperityAchievement body = ProsperityAchievementTestSamples.sample();
        body.setId(1L);
        mockMvc.perform(put("/commonProsperity/achievement")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("GTFY-CG-API-018 DELETE 单条")
    void api018_delete() throws Exception
    {
        when(bizCommonProsperityAchievementService.deleteBizCommonProsperityAchievementByIds(any())).thenReturn(1);
        mockMvc.perform(delete("/commonProsperity/achievement/7"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("GTFY-CG-API-023 失败可读 msg")
    void api023_errorMsg() throws Exception
    {
        when(bizCommonProsperityAchievementService.insertBizCommonProsperityAchievement(any()))
                .thenThrow(new ServiceException("统计范围格式须为YYYY-MM（如2026-05）"));
        BizCommonProsperityAchievement body = ProsperityAchievementTestSamples.sample();
        body.setStatPeriod("2026-13");
        mockMvc.perform(post("/commonProsperity/achievement")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500))
                .andExpect(jsonPath("$.msg").value(containsString("YYYY-MM")));
    }

    private static BizCommonProsperityAchievement sample(Long id)
    {
        BizCommonProsperityAchievement r = ProsperityAchievementTestSamples.sample();
        r.setId(id);
        return r;
    }
}
