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

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.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.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.architecture.domain.BizBreedingStandard;
import com.ruoyi.web.modules.architecture.service.IBizBreedingStandardService;

/**
 * 接口测试（MockMvc + Mock Service），对照 doc/养殖标准/养殖标准管理测试用例.md 二、YZ-BZ-API-001～017。
 * <p>YZ-BZ-API-018/019 依赖完整 Spring Security 过滤器链，建议用已启动环境 + Postman，或另行编写 {@code @SpringBootTest} 全链路用例。</p>
 */
@ExtendWith(MockitoExtension.class)
@DisplayName("养殖标准 HTTP 接口 MockMvc")
class BizBreedingStandardControllerApiTest
{

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Mock
    private IBizBreedingStandardService bizBreedingStandardService;

    @InjectMocks
    private BizBreedingStandardController 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("YZ-BZ-API-001 GET /list 分页与 code=200")
    void api001_list() throws Exception
    {
        when(bizBreedingStandardService.selectBizBreedingStandardList(any()))
                .thenReturn(Collections.singletonList(sample(1L)));
        mockMvc.perform(get("/breeding/standard/list").param("pageNum", "1").param("pageSize", "10"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.rows").isArray())
                .andExpect(jsonPath("$.rows.length()").value(1));
    }

    @Test
    @DisplayName("YZ-BZ-API-002 GET /list keyword + standardType 透传 Service")
    void api002_listFilter() throws Exception
    {
        when(bizBreedingStandardService.selectBizBreedingStandardList(any())).thenReturn(Collections.emptyList());
        mockMvc.perform(get("/breeding/standard/list")
                .param("keyword", "免疫")
                .param("standardType", "001003"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("YZ-BZ-API-005 GET /{id} 详情字段")
    void api005_getDetail() throws Exception
    {
        when(bizBreedingStandardService.selectBizBreedingStandardById(2L)).thenReturn(sample(2L));
        mockMvc.perform(get("/breeding/standard/2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.standardName").exists())
                .andExpect(jsonPath("$.data.contentFileName").exists())
                .andExpect(jsonPath("$.data.publishStatus").exists())
                .andExpect(jsonPath("$.data.kbSyncStatus").exists());
    }

    @Test
    @DisplayName("YZ-BZ-API-006 GET /{id} 不存在时 data 为空（当前实现）")
    void api006_getMissing() throws Exception
    {
        when(bizBreedingStandardService.selectBizBreedingStandardById(999999L)).thenReturn(null);
        mockMvc.perform(get("/breeding/standard/999999"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("YZ-BZ-API-003 POST 新增成功")
    void api003_add() throws Exception
    {
        when(bizBreedingStandardService.insertBizBreedingStandard(any())).thenReturn(1);
        BizBreedingStandard body = sample(null);
        mockMvc.perform(post("/breeding/standard")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("YZ-BZ-API-007 PUT 修改成功")
    void api007_put() throws Exception
    {
        when(bizBreedingStandardService.updateBizBreedingStandard(any())).thenReturn(1);
        BizBreedingStandard body = sample(8L);
        mockMvc.perform(put("/breeding/standard")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("YZ-BZ-API-008 PUT 业务异常 → GlobalExceptionHandler")
    void api008_putBusinessError() throws Exception
    {
        when(bizBreedingStandardService.updateBizBreedingStandard(any()))
                .thenThrow(new ServiceException("仅「未发布」状态允许编辑"));
        BizBreedingStandard body = sample(8L);
        mockMvc.perform(put("/breeding/standard")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("YZ-BZ-API-009 DELETE 成功")
    void api009_delete() throws Exception
    {
        when(bizBreedingStandardService.deleteBizBreedingStandardByIds(any())).thenReturn(1);
        mockMvc.perform(delete("/breeding/standard/7"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("YZ-BZ-API-010 DELETE 已发布禁止")
    void api010_deleteForbidden() throws Exception
    {
        when(bizBreedingStandardService.deleteBizBreedingStandardByIds(any()))
                .thenThrow(new ServiceException("已发布的数据不可删除，请先下架"));
        mockMvc.perform(delete("/breeding/standard/7"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("YZ-BZ-API-011 POST syncKb 成功")
    void api011_syncKb() throws Exception
    {
        when(bizBreedingStandardService.syncKb(11L)).thenReturn(1);
        mockMvc.perform(post("/breeding/standard/syncKb/11"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("YZ-BZ-API-012 POST syncKb 失败")
    void api012_syncKbFail() throws Exception
    {
        when(bizBreedingStandardService.syncKb(12L)).thenThrow(new ServiceException("仅「未发布且未同步」可操作同步（本地占位，未调用知识库服务）"));
        mockMvc.perform(post("/breeding/standard/syncKb/12"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("YZ-BZ-API-013 POST removeKb")
    void api013_removeKb() throws Exception
    {
        when(bizBreedingStandardService.removeKb(13L)).thenReturn(1);
        mockMvc.perform(post("/breeding/standard/removeKb/13"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("YZ-BZ-API-014 POST publish")
    void api014_publish() throws Exception
    {
        when(bizBreedingStandardService.publish(14L)).thenReturn(1);
        mockMvc.perform(post("/breeding/standard/publish/14"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("YZ-BZ-API-015 POST publish 未同步禁止")
    void api015_publishFail() throws Exception
    {
        when(bizBreedingStandardService.publish(15L)).thenThrow(new ServiceException("仅「未发布且已同步」可发布"));
        mockMvc.perform(post("/breeding/standard/publish/15"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("YZ-BZ-API-016 POST offline")
    void api016_offline() throws Exception
    {
        when(bizBreedingStandardService.offline(16L)).thenReturn(1);
        mockMvc.perform(post("/breeding/standard/offline/16"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("YZ-BZ-API-017 POST offline 非已发布禁止")
    void api017_offlineFail() throws Exception
    {
        when(bizBreedingStandardService.offline(17L)).thenThrow(new ServiceException("仅「已发布」可下架"));
        mockMvc.perform(post("/breeding/standard/offline/17"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    private static BizBreedingStandard sample(Long id)
    {
        BizBreedingStandard r = new BizBreedingStandard();
        r.setId(id);
        r.setStandardName("养");
        r.setStandardType("001001");
        r.setIntroduction("简介");
        r.setContentFileUrl("http://localhost/f");
        r.setContentFilePath(Constants.RESOURCE_PREFIX + "/upload/2026/a.pdf");
        r.setContentFileName("a.pdf");
        r.setPublishStatus(0);
        r.setKbSyncStatus(0);
        return r;
    }
}
