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

/**
 * 接口测试（MockMvc + Mock Service），对照 doc/饲喂标准/饲喂标准管理测试用例.md 二、WF-BZ-API-001～022。
 * <p>WF-BZ-API-023/024 依赖完整 Spring Security 过滤器链；WF-BZ-API-025/026 建议在集成环境或补充校验器后执行。</p>
 */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("饲喂标准 HTTP 接口 MockMvc")
class BizFeedingStandardControllerApiTest
{

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Mock
    private IBizFeedingStandardService bizFeedingStandardService;

    @InjectMocks
    private BizFeedingStandardController 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("WF-BZ-API-001 GET /list 分页与 code=200")
    void api001_list() throws Exception
    {
        when(bizFeedingStandardService.selectBizFeedingStandardList(any()))
                .thenReturn(Collections.singletonList(sample(1L)));
        mockMvc.perform(get("/feeding/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("WF-BZ-API-002 GET /list keyword 透传")
    void api002_listKeyword() throws Exception
    {
        when(bizFeedingStandardService.selectBizFeedingStandardList(any())).thenReturn(Collections.emptyList());
        mockMvc.perform(get("/feeding/standard/list").param("keyword", "配方"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("WF-BZ-API-003 GET /list standardType 精确")
    void api003_listType() throws Exception
    {
        when(bizFeedingStandardService.selectBizFeedingStandardList(any())).thenReturn(Collections.emptyList());
        mockMvc.perform(get("/feeding/standard/list").param("standardType", "001005"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("WF-BZ-API-004 GET /list keyword + standardType 组合")
    void api004_listCombo() throws Exception
    {
        when(bizFeedingStandardService.selectBizFeedingStandardList(any())).thenReturn(Collections.emptyList());
        mockMvc.perform(get("/feeding/standard/list").param("keyword", "测").param("standardType", "001006"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("WF-BZ-API-005 POST 新增成功")
    void api005_add() throws Exception
    {
        when(bizFeedingStandardService.insertBizFeedingStandard(any())).thenReturn(1);
        BizFeedingStandard body = sample(null);
        mockMvc.perform(post("/feeding/standard")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("WF-BZ-API-006 POST 新增名称非法 → ServiceException")
    void api006_addBadName() throws Exception
    {
        when(bizFeedingStandardService.insertBizFeedingStandard(any()))
                .thenThrow(new ServiceException("标准名称须为1～20个字符"));
        BizFeedingStandard body = sample(null);
        body.setStandardName("12");
        mockMvc.perform(post("/feeding/standard")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("WF-BZ-API-007 POST 新增类型非法")
    void api007_addBadType() throws Exception
    {
        when(bizFeedingStandardService.insertBizFeedingStandard(any()))
                .thenThrow(new ServiceException("标准类型无效，请选择资讯类别中的类型"));
        BizFeedingStandard body = sample(null);
        body.setStandardType("999999");
        mockMvc.perform(post("/feeding/standard")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("WF-BZ-API-008 POST 新增简介超长")
    void api008_addLongIntro() throws Exception
    {
        when(bizFeedingStandardService.insertBizFeedingStandard(any()))
                .thenThrow(new ServiceException("简介不能超过50个字符"));
        BizFeedingStandard body = sample(null);
        body.setIntroduction(repeat('x', 51));
        mockMvc.perform(post("/feeding/standard")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("WF-BZ-API-009 GET /{id} 详情字段")
    void api009_getDetail() throws Exception
    {
        when(bizFeedingStandardService.selectBizFeedingStandardById(2L)).thenReturn(sample(2L));
        mockMvc.perform(get("/feeding/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("WF-BZ-API-010 GET /{id} 不存在")
    void api010_getMissing() throws Exception
    {
        when(bizFeedingStandardService.selectBizFeedingStandardById(999999L)).thenReturn(null);
        mockMvc.perform(get("/feeding/standard/999999"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("WF-BZ-API-011 PUT 修改成功")
    void api011_put() throws Exception
    {
        when(bizFeedingStandardService.updateBizFeedingStandard(any())).thenReturn(1);
        BizFeedingStandard body = sample(8L);
        mockMvc.perform(put("/feeding/standard")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("WF-BZ-API-012 PUT 已发布拒绝")
    void api012_putPublished() throws Exception
    {
        when(bizFeedingStandardService.updateBizFeedingStandard(any()))
                .thenThrow(new ServiceException("仅「未发布」状态允许编辑"));
        BizFeedingStandard body = sample(8L);
        mockMvc.perform(put("/feeding/standard")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("WF-BZ-API-013 DELETE 未同步可删")
    void api013_delete() throws Exception
    {
        when(bizFeedingStandardService.deleteBizFeedingStandardByIds(any())).thenReturn(1);
        mockMvc.perform(delete("/feeding/standard/7"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

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

    @Test
    @DisplayName("WF-BZ-API-015 DELETE 未发布已同步（Service 内置移出语义）")
    void api015_deleteSynced() throws Exception
    {
        when(bizFeedingStandardService.deleteBizFeedingStandardByIds(any())).thenReturn(1);
        mockMvc.perform(delete("/feeding/standard/71"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("WF-BZ-API-016 POST syncKb 首次同步")
    void api016_syncKb() throws Exception
    {
        when(bizFeedingStandardService.syncKb(11L)).thenReturn(1);
        mockMvc.perform(post("/feeding/standard/syncKb/11"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("WF-BZ-API-017 POST syncKb 重复/非法")
    void api017_syncKbFail() throws Exception
    {
        when(bizFeedingStandardService.syncKb(12L)).thenThrow(new ServiceException("仅「未发布且未同步」可操作同步（未调用知识库服务）"));
        mockMvc.perform(post("/feeding/standard/syncKb/12"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500));
    }

    @Test
    @DisplayName("WF-BZ-API-018 POST removeKb")
    void api018_removeKb() throws Exception
    {
        when(bizFeedingStandardService.removeKb(13L)).thenReturn(1);
        mockMvc.perform(post("/feeding/standard/removeKb/13"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("WF-BZ-API-019 POST publish")
    void api019_publish() throws Exception
    {
        when(bizFeedingStandardService.publish(14L)).thenReturn(1);
        mockMvc.perform(post("/feeding/standard/publish/14"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

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

    @Test
    @DisplayName("WF-BZ-API-021 POST offline 成功")
    void api021_offline() throws Exception
    {
        when(bizFeedingStandardService.offline(16L)).thenReturn(1);
        mockMvc.perform(post("/feeding/standard/offline/16"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

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

    private static String repeat(char c, int n)
    {
        char[] a = new char[n];
        java.util.Arrays.fill(a, c);
        return new String(a);
    }

    private static BizFeedingStandard sample(Long id)
    {
        BizFeedingStandard r = new BizFeedingStandard();
        r.setId(id);
        r.setStandardName("饲");
        r.setStandardType("001005");
        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;
    }
}
