package cn.nianxx.thhotel.platform.hotel.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.hotel.domain.PlatformUserHotelEntity;
import cn.nianxx.thhotel.platform.hotel.mapper.PlatformHotelMapper;
import cn.nianxx.thhotel.platform.hotel.mapper.PlatformUserHotelMapper;
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 MybatisPlatformHotelRepositoryTest {

    @Mock
    private PlatformHotelMapper hotelMapper;
    @Mock
    private PlatformUserHotelMapper userHotelMapper;

    @Test
    void shouldIgnoreDuplicateKeyWhenEnsuringUserHotel() {
        MybatisPlatformHotelRepository repository = new MybatisPlatformHotelRepository(hotelMapper, userHotelMapper);
        when(userHotelMapper.selectOne(any(Wrapper.class)))
                .thenReturn(null)
                .thenReturn(existingUserHotel());
        doThrow(new DuplicateKeyException("duplicate user hotel"))
                .when(userHotelMapper).insert(any(PlatformUserHotelEntity.class));

        assertThatNoException().isThrownBy(() -> repository.ensureUserHotel(1L, "HOTEL-TEST", true));
    }

    private PlatformUserHotelEntity existingUserHotel() {
        PlatformUserHotelEntity relation = new PlatformUserHotelEntity();
        relation.setId(10L);
        relation.setUserId(1L);
        relation.setHotelId("HOTEL-TEST");
        relation.setDefaultHotel(true);
        return relation;
    }
}
