package com.ruoyi.web.modules.video.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.video.LivestockMonitorTestSamples;
import com.ruoyi.web.modules.video.domain.BizLivestockMonitor;
import com.ruoyi.web.modules.video.domain.MonitorOwnerOption;
import com.ruoyi.web.modules.industryservice.domain.vo.YakAssetSyncResultVo;
import com.ruoyi.web.modules.video.service.IBizLivestockMonitorService;
import com.ruoyi.web.modules.video.support.LivestockMonitorRules;

@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("畜牧监控 HTTP 接口 MockMvc")
class BizLivestockMonitorControllerApiTest
{

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

    @Mock
    private IBizLivestockMonitorService bizLivestockMonitorService;

    @InjectMocks
    private BizLivestockMonitorController 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
    {
        BizLivestockMonitor row = LivestockMonitorTestSamples.sampleWithId(1L);
        when(bizLivestockMonitorService.selectBizLivestockMonitorList(any()))
                .thenReturn(Collections.singletonList(row));
        mockMvc.perform(get("/videoSurveillance/livestockMonitor/list")
                .param("monitorName", "圈舍")
                .param("ownerType", "1")
                .param("ownerId", "101"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("GET /ownerOptions")
    void ownerOptions() throws Exception
    {
        MonitorOwnerOption opt = new MonitorOwnerOption();
        opt.setOwnerType(LivestockMonitorRules.OWNER_TYPE_PASTURE);
        opt.setOwnerId(LivestockMonitorTestSamples.PASTURE_OWNER_ID);
        opt.setOwnerName("巴青牧场");
        when(bizLivestockMonitorService.selectOwnerOptions("巴青"))
                .thenReturn(Collections.singletonList(opt));
        mockMvc.perform(get("/videoSurveillance/livestockMonitor/ownerOptions")
                .param("keyword", "巴青"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data[0].ownerName").value("巴青牧场"));
    }

    @Test
    @DisplayName("GET /{id}")
    void getInfo() throws Exception
    {
        when(bizLivestockMonitorService.selectBizLivestockMonitorById(1L))
                .thenReturn(LivestockMonitorTestSamples.sampleWithId(1L));
        mockMvc.perform(get("/videoSurveillance/livestockMonitor/1"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.monitorName").value("圈舍监控1"));
    }

    @Test
    @DisplayName("POST 新增")
    void add() throws Exception
    {
        when(bizLivestockMonitorService.insertBizLivestockMonitor(any())).thenReturn(1);
        mockMvc.perform(post("/videoSurveillance/livestockMonitor")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(LivestockMonitorTestSamples.samplePastureMonitor())))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("PUT 修改")
    void edit() throws Exception
    {
        BizLivestockMonitor row = LivestockMonitorTestSamples.sampleWithId(1L);
        when(bizLivestockMonitorService.updateBizLivestockMonitor(any())).thenReturn(1);
        mockMvc.perform(put("/videoSurveillance/livestockMonitor")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(row)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("DELETE 删除")
    void removeByIds() throws Exception
    {
        when(bizLivestockMonitorService.deleteBizLivestockMonitorByIds(any(), eq("tester"))).thenReturn(1);
        mockMvc.perform(delete("/videoSurveillance/livestockMonitor/1"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("GET /playUrl")
    void playUrl() throws Exception
    {
        com.ruoyi.web.modules.video.domain.vo.LivestockMonitorPlayUrlVo vo =
                new com.ruoyi.web.modules.video.domain.vo.LivestockMonitorPlayUrlVo();
        vo.setMonitorId("50001");
        vo.setVideoUrl("https://example.com/live/50001.m3u8");
        when(bizLivestockMonitorService.getPlayUrlByMonitorId("50001")).thenReturn(vo);
        mockMvc.perform(get("/videoSurveillance/livestockMonitor/playUrl")
                .param("monitorId", "50001"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.videoUrl").value("https://example.com/live/50001.m3u8"));
    }

    @Test
    @DisplayName("POST /sync")
    void sync() throws Exception
    {
        YakAssetSyncResultVo vo = new YakAssetSyncResultVo();
        vo.setInsertCount(2);
        when(bizLivestockMonitorService.syncFromThirdParty("tester")).thenReturn(vo);
        mockMvc.perform(post("/videoSurveillance/livestockMonitor/sync"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.insertCount").value(2));
    }
}
