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

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
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.fasterxml.jackson.databind.SerializationFeature;
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.framework.web.exception.GlobalExceptionHandler;
import com.ruoyi.web.modules.technology.PracticalTrainingTestSamples;
import com.ruoyi.web.modules.technology.domain.BizPracticalTraining;
import com.ruoyi.web.modules.technology.service.IBizPracticalTrainingService;
import com.ruoyi.web.modules.technology.support.PracticalTrainingRules;

@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("实战业务培训 HTTP 接口 MockMvc")
class BizPracticalTrainingControllerApiTest
{

    private final ObjectMapper objectMapper = new ObjectMapper()
            .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    @Mock
    private IBizPracticalTrainingService bizPracticalTrainingService;

    @InjectMocks
    private BizPracticalTrainingController 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("GET /list")
    void list() throws Exception
    {
        BizPracticalTraining row = PracticalTrainingTestSamples.sampleDraft();
        row.setId(1L);
        row.setEnrollStatus(PracticalTrainingRules.ENROLL_STATUS_NOT_STARTED);
        row.setEnrollStatusName("未开始");
        when(bizPracticalTrainingService.selectBizPracticalTrainingList(any()))
                .thenReturn(Collections.singletonList(row));
        mockMvc.perform(get("/techService/practicalTraining/list")
                .param("trainingTopic", "牧业实战测试")
                .param("startDate", "2025-08-01")
                .param("endDate", "2025-08-31"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("POST 新增")
    void add() throws Exception
    {
        when(bizPracticalTrainingService.insertBizPracticalTraining(any())).thenReturn(1);
        mockMvc.perform(post("/techService/practicalTraining")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(PracticalTrainingTestSamples.sampleDraft())))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("GET /{id}")
    void getDetail() throws Exception
    {
        BizPracticalTraining row = PracticalTrainingTestSamples.sampleDraft();
        row.setId(2L);
        row.setCanOffline(false);
        when(bizPracticalTrainingService.selectBizPracticalTrainingById(2L)).thenReturn(row);
        mockMvc.perform(get("/techService/practicalTraining/2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.trainingTopic").value("牧业实战测试"));
    }

    @Test
    @DisplayName("PUT 修改")
    void editUpdate() throws Exception
    {
        when(bizPracticalTrainingService.updateBizPracticalTraining(any())).thenReturn(1);
        BizPracticalTraining body = PracticalTrainingTestSamples.sampleDraft();
        body.setId(3L);
        mockMvc.perform(put("/techService/practicalTraining")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("POST 发布")
    void publish() throws Exception
    {
        when(bizPracticalTrainingService.publish(4L)).thenReturn(1);
        mockMvc.perform(post("/techService/practicalTraining/publish/4"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("POST 下架")
    void offline() throws Exception
    {
        when(bizPracticalTrainingService.offline(5L)).thenReturn(1);
        mockMvc.perform(post("/techService/practicalTraining/offline/5"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("DELETE 删除")
    void deleteSingle() throws Exception
    {
        when(bizPracticalTrainingService.deleteBizPracticalTrainingByIds(any(), eq("tester"))).thenReturn(1);
        mockMvc.perform(delete("/techService/practicalTraining/6"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }
}
