package com.ruoyi.web.controller.system;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.framework.web.service.PasswordTransferCryptoService;
import com.ruoyi.framework.web.service.SysRegisterService;
import com.ruoyi.system.service.ISysConfigService;

class SysRegisterControllerPasswordTransferTest
{
    @Test
    void shouldDecryptPasswordBeforeCallingRegisterService() throws Exception
    {
        SysRegisterService registerService = mock(SysRegisterService.class);
        ISysConfigService configService = mock(ISysConfigService.class);
        PasswordTransferCryptoService passwordTransferCryptoService = mock(PasswordTransferCryptoService.class);
        when(configService.selectConfigByKey("sys.account.registerUser")).thenReturn("true");
        when(passwordTransferCryptoService.decrypt("cipher")).thenReturn("admin123");
        when(registerService.register(any(RegisterBody.class))).thenReturn("");

        SysRegisterController controller = new SysRegisterController();
        ReflectionTestUtils.setField(controller, "registerService", registerService);
        ReflectionTestUtils.setField(controller, "configService", configService);
        ReflectionTestUtils.setField(controller, "passwordTransferCryptoService", passwordTransferCryptoService);

        MockMvc mockMvc = MockMvcBuilders.standaloneSetup(controller).build();

        mockMvc.perform(post("/register")
                .contentType("application/json")
                .content("{\"username\":\"u1\",\"password\":\"cipher\",\"code\":\"1\",\"uuid\":\"u\"}"))
                .andExpect(status().isOk());

        verify(passwordTransferCryptoService).decrypt("cipher");
        ArgumentCaptor<RegisterBody> captor = ArgumentCaptor.forClass(RegisterBody.class);
        verify(registerService).register(captor.capture());
        assertEquals("admin123", captor.getValue().getPassword());
    }
}
