package com.ruoyi.web.modules.trading.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 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("TradePartnerAccountAssigner")
class TradePartnerAccountAssignerTest
{
    @Mock
    private ISysUserService sysUserService;

    @Mock
    private ISysConfigService configService;

    @Mock
    private SysRoleMapper sysRoleMapper;

    @InjectMocks
    private TradePartnerAccountAssigner assigner;

    @Test
    @DisplayName("按 role_key 绑定供应商角色")
    void createAccountSupplierRole()
    {
        SysRole role = new SysRole();
        role.setRoleId(103L);
        when(sysRoleMapper.checkRoleKeyUnique(TradePartnerAccountRules.ROLE_KEY_SUPPLIER)).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("扎西供应商", "13800138000", 12L,
                TradePartnerAccountRules.ROLE_KEY_SUPPLIER, "admin");
        assertEquals("zxgys12", user.getUserName());
        verify(sysRoleMapper).checkRoleKeyUnique(TradePartnerAccountRules.ROLE_KEY_SUPPLIER);
    }

    @Test
    @DisplayName("角色不存在")
    void roleMissing()
    {
        when(sysUserService.checkUserNameUnique(any())).thenReturn(true);
        when(sysRoleMapper.checkRoleKeyUnique(TradePartnerAccountRules.ROLE_KEY_SUPPLIER)).thenReturn(null);
        assertThrows(ServiceException.class, () -> assigner.createAccount("甲", "13800138000", 1L,
                TradePartnerAccountRules.ROLE_KEY_SUPPLIER, "admin"));
    }
}
