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

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.when;
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.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

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.industryservice.YakDiseaseWarningTestSamples;
import com.ruoyi.web.modules.industryservice.domain.vo.YakAssetSyncResultVo;
import com.ruoyi.web.modules.industryservice.service.IBizYakDiseaseWarningService;
import com.ruoyi.web.modules.industryservice.support.YakDiseaseWarningRules;

@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("牦牛疾病预警后台 HTTP MockMvc")
class BizYakDiseaseWarningControllerApiTest
{
    @Mock
    private IBizYakDiseaseWarningService bizYakDiseaseWarningService;

    @InjectMocks
    private BizYakDiseaseWarningController 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("warnTester");
        u.setPassword("x");
        Set<String> perms = new HashSet<>();
        perms.add(Constants.ALL_PERMISSION);
        LoginUser lu = new LoginUser(1L, 100L, u, perms);
        SecurityContextHolder.getContext().setAuthentication(
                new UsernamePasswordAuthenticationToken(lu, "", lu.getAuthorities()));
    }

    @Test
    @DisplayName("ZCZX-MYNBJY-API-001 GET /list")
    void api001_list() throws Exception
    {
        when(bizYakDiseaseWarningService.selectBizYakDiseaseWarningList(any()))
                .thenReturn(Collections.singletonList(YakDiseaseWarningTestSamples.recentWarning()));
        mockMvc.perform(get("/dataModel/yakDiseaseWarning/list"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("ZCZX-MYNBJY-API-005 日期颠倒")
    void api005_invalidDate() throws Exception
    {
        when(bizYakDiseaseWarningService.selectBizYakDiseaseWarningList(any()))
                .thenThrow(new ServiceException(YakDiseaseWarningRules.MSG_DATE_RANGE_INVALID));
        mockMvc.perform(get("/dataModel/yakDiseaseWarning/list")
                .param("startDate", "2026-05-10")
                .param("endDate", "2026-05-01"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("ZCZX-MYNBJY-API-011 GET /{id}")
    void api011_detail() throws Exception
    {
        when(bizYakDiseaseWarningService.selectBizYakDiseaseWarningById(eq(YakDiseaseWarningTestSamples.WARNING_ID),
                isNull())).thenReturn(YakDiseaseWarningTestSamples.recentWarning());
        mockMvc.perform(get("/dataModel/yakDiseaseWarning/" + YakDiseaseWarningTestSamples.WARNING_ID))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.pastureName").value("牧场甲"));
    }

    @Test
    @DisplayName("ZCZX-MYNBJY-API-015 POST /sync")
    void api015_sync() throws Exception
    {
        YakAssetSyncResultVo vo = new YakAssetSyncResultVo();
        vo.setInsertCount(1);
        when(bizYakDiseaseWarningService.syncFromThirdParty()).thenReturn(vo);
        mockMvc.perform(post("/dataModel/yakDiseaseWarning/sync"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.insertCount").value(1));
    }

    @Test
    @DisplayName("ZCZX-MYNBJY-API-019 同步处理中")
    void api019_syncBusy() throws Exception
    {
        when(bizYakDiseaseWarningService.syncFromThirdParty())
                .thenThrow(new ServiceException(YakDiseaseWarningRules.MSG_SYNC_IN_PROGRESS));
        mockMvc.perform(post("/dataModel/yakDiseaseWarning/sync"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.msg").value(YakDiseaseWarningRules.MSG_SYNC_IN_PROGRESS));
    }
}
