package cn.nianxx.thhotel.platform.access.repository;

import static org.assertj.core.api.Assertions.assertThatNoException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;

import cn.nianxx.thhotel.platform.access.domain.PlatformRolePermissionEntity;
import cn.nianxx.thhotel.platform.access.domain.PlatformUserRoleEntity;
import cn.nianxx.thhotel.platform.access.mapper.PlatformPermissionMapper;
import cn.nianxx.thhotel.platform.access.mapper.PlatformRoleMapper;
import cn.nianxx.thhotel.platform.access.mapper.PlatformRolePermissionMapper;
import cn.nianxx.thhotel.platform.access.mapper.PlatformUserRoleMapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.dao.DuplicateKeyException;

@ExtendWith(MockitoExtension.class)
@SuppressWarnings({"rawtypes", "unchecked"})
class MybatisPlatformAccessRepositoryTest {

    @Mock
    private PlatformRoleMapper roleMapper;
    @Mock
    private PlatformPermissionMapper permissionMapper;
    @Mock
    private PlatformUserRoleMapper userRoleMapper;
    @Mock
    private PlatformRolePermissionMapper rolePermissionMapper;

    @Test
    void shouldIgnoreDuplicateKeyWhenEnsuringRolePermission() {
        MybatisPlatformAccessRepository repository = repository();
        when(rolePermissionMapper.selectCount(any(Wrapper.class))).thenReturn(0L);
        doThrow(new DuplicateKeyException("duplicate role permission"))
                .when(rolePermissionMapper).insert(any(PlatformRolePermissionEntity.class));

        assertThatNoException().isThrownBy(() -> repository.ensureRolePermission(1L, 2L));
    }

    @Test
    void shouldIgnoreDuplicateKeyWhenEnsuringUserRole() {
        MybatisPlatformAccessRepository repository = repository();
        when(userRoleMapper.selectCount(any(Wrapper.class))).thenReturn(0L);
        doThrow(new DuplicateKeyException("duplicate user role"))
                .when(userRoleMapper).insert(any(PlatformUserRoleEntity.class));

        assertThatNoException().isThrownBy(() -> repository.ensureUserRole(1L, 2L));
    }

    private MybatisPlatformAccessRepository repository() {
        return new MybatisPlatformAccessRepository(roleMapper, permissionMapper, userRoleMapper, rolePermissionMapper);
    }
}
