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

import static org.assertj.core.api.Assertions.assertThatThrownBy;

import cn.nianxx.thhotel.ThHotelApplication;
import cn.nianxx.thhotel.platform.hotel.common.enums.PlatformHotelStatus;
import cn.nianxx.thhotel.platform.hotel.domain.PlatformHotelEntity;
import java.time.LocalDateTime;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.test.context.ActiveProfiles;

@SpringBootTest(
        classes = ThHotelApplication.class,
        properties = {
                "spring.datasource.url=jdbc:h2:mem:m005_single_active_hotel;MODE=MySQL;DATABASE_TO_LOWER=TRUE;CASE_INSENSITIVE_IDENTIFIERS=TRUE",
                "auth.bootstrap.admin.username=",
                "auth.bootstrap.admin.password=",
                "auth.bootstrap.default-hotel-id="
        })
@ActiveProfiles("test")
class PlatformHotelSingleActiveConstraintTest {

    @Autowired
    private PlatformHotelRepository hotelRepository;

    @Test
    void shouldRejectSecondActiveHotelAtDatabaseLevel() {
        hotelRepository.insertHotel(hotel("M005-ACTIVE-A", PlatformHotelStatus.ACTIVE));

        assertThatThrownBy(() -> hotelRepository.insertHotel(hotel("M005-ACTIVE-B", PlatformHotelStatus.ACTIVE)))
                .isInstanceOf(DataIntegrityViolationException.class);
    }

    private PlatformHotelEntity hotel(String hotelId, PlatformHotelStatus status) {
        LocalDateTime now = LocalDateTime.now();
        PlatformHotelEntity hotel = new PlatformHotelEntity();
        hotel.setHotelId(hotelId);
        hotel.setHotelName(hotelId);
        hotel.setHotelStatus(status.name());
        hotel.setTimeZone("Asia/Bangkok");
        hotel.setSortOrder(10);
        hotel.setCreatedAt(now);
        hotel.setUpdatedAt(now);
        return hotel;
    }
}
