package com.ruoyi.web.modules.farming.support;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.modules.farming.TechResourceTestSamples;
import com.ruoyi.web.modules.farming.domain.BizTechResource;
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;

@ExtendWith(MockitoExtension.class)
@DisplayName("TechResourceAccountAssigner")
class TechResourceAccountAssignerTest
{
    @Mock
    private ISysUserService sysUserService;

    @Mock
    private ISysConfigService configService;

    @Mock
    private SysRoleMapper sysRoleMapper;

    @InjectMocks
    private TechResourceAccountAssigner assigner;

    @Test
    @DisplayName("专家绑定 exp 角色")
    void createAccountExpert()
    {
        BizTechResource resource = TechResourceTestSamples.sampleExpertDraft();
        resource.setId(12L);
        resource.setResourceName("张专家");
        SysRole role = new SysRole();
        role.setRoleId(101L);
        when(sysRoleMapper.checkRoleKeyUnique(TechResourceRules.ROLE_KEY_EXPERT)).thenReturn(role);
        when(sysUserService.checkUserNameUnique(any())).thenReturn(true);
        when(configService.selectConfigByKey("sys.user.initPassword")).thenReturn("123456");
        when(sysUserService.insertUser(any())).thenAnswer(inv -> {
            SysUser u = inv.getArgument(0);
            u.setUserId(1L);
            return 1;
        });

        SysUser user = assigner.createAccount(resource, "admin");
        assertEquals("zzj12", user.getUserName());
        verify(sysRoleMapper).checkRoleKeyUnique(TechResourceRules.ROLE_KEY_EXPERT);
    }

    @Test
    @DisplayName("角色不存在")
    void roleMissing()
    {
        BizTechResource resource = TechResourceTestSamples.sampleExpertDraft();
        resource.setId(1L);
        when(sysUserService.checkUserNameUnique(any())).thenReturn(true);
        when(sysRoleMapper.checkRoleKeyUnique(TechResourceRules.ROLE_KEY_EXPERT)).thenReturn(null);
        assertThrows(ServiceException.class, () -> assigner.createAccount(resource, "admin"));
    }
}
