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

import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
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.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.web.modules.store.constant.ShopConstants;
import com.ruoyi.web.modules.store.dto.ShopSettingsDTO;
import com.ruoyi.web.modules.store.service.IShopGlobalConfigService;
import com.ruoyi.web.modules.store.vo.ShopSettingsVO;

@ExtendWith(MockitoExtension.class)
class ShopGlobalSettingControllerTest
{
    @Mock
    private IShopGlobalConfigService globalConfigService;

    @Spy
    @InjectMocks
    private ShopGlobalSettingController controller;

    private MockMvc mockMvc;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @BeforeEach
    void setUp() throws Exception
    {
        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
        org.mockito.Mockito.lenient().doReturn("admin").when(controller).getUsername();
    }

    @Test
    void getSettings_returns200() throws Exception
    {
        ShopSettingsVO vo = new ShopSettingsVO();
        vo.setDefaultAuditPass(ShopConstants.AUDIT_PASS_NO);
        vo.setMaxSubAdmin(5);
        when(globalConfigService.getGlobalSettings()).thenReturn(vo);

        mockMvc.perform(get("/agri/shopSetting"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.defaultAuditPass").value("0"))
                .andExpect(jsonPath("$.data.maxSubAdmin").value(5));
    }

    @Test
    void updateSettings_returnsMsg() throws Exception
    {
        ShopSettingsDTO dto = new ShopSettingsDTO();
        dto.setDefaultAuditPass(ShopConstants.AUDIT_PASS_YES);
        dto.setMaxSubAdmin(10);

        mockMvc.perform(put("/agri/shopSetting")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(dto)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.msg").value(ShopConstants.MSG_SETTINGS_SAVED));

        verify(globalConfigService).updateGlobalSettings(org.mockito.ArgumentMatchers.any(), eq("admin"));
    }
}
