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

import static org.assertj.core.api.Assertions.assertThat;
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 cn.nianxx.thhotel.platform.identity.common.enums.PlatformUserStatus;
import cn.nianxx.thhotel.platform.identity.domain.PlatformUserEntity;
import cn.nianxx.thhotel.platform.identity.repository.PlatformIdentityRepository;
import java.time.LocalDateTime;
import org.junit.jupiter.api.AfterEach;
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.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ActiveProfiles;

@SpringBootTest(
        classes = ThHotelApplication.class,
        properties = {
                "spring.datasource.url=jdbc:h2:mem:m003_hotel_repository_review;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 PlatformHotelRepositoryTest {

    @Autowired
    private PlatformHotelRepository hotelRepository;

    @Autowired
    private PlatformIdentityRepository identityRepository;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @AfterEach
    void cleanReviewRows() {
        jdbcTemplate.update("DELETE FROM platform_user_hotel WHERE hotel_id LIKE 'M003-REVIEW-%'");
        jdbcTemplate.update("DELETE FROM platform_hotel WHERE hotel_id LIKE 'M003-REVIEW-%'");
        jdbcTemplate.update("DELETE FROM platform_user WHERE username LIKE 'm003-review-%'");
    }

    @Test
    void shouldKeepOnlyOneDefaultHotelForUser() {
        PlatformUserEntity user = user("m003-review-hotel-user");
        identityRepository.insertUser(user);
        hotelRepository.insertHotel(hotel("M003-REVIEW-HOTEL-A", PlatformHotelStatus.DISABLED));
        hotelRepository.insertHotel(hotel("M003-REVIEW-HOTEL-B", PlatformHotelStatus.DISABLED));

        hotelRepository.ensureUserHotel(user.getId(), "M003-REVIEW-HOTEL-A", true);
        hotelRepository.ensureUserHotel(user.getId(), "M003-REVIEW-HOTEL-B", true);

        Integer defaultCount = jdbcTemplate.queryForObject("""
                SELECT COUNT(*)
                FROM platform_user_hotel
                WHERE user_id = ?
                  AND default_hotel = 1
                """, Integer.class, user.getId());
        Boolean hotelADefault = jdbcTemplate.queryForObject("""
                SELECT default_hotel
                FROM platform_user_hotel
                WHERE user_id = ?
                  AND hotel_id = 'M003-REVIEW-HOTEL-A'
                """, Boolean.class, user.getId());
        Boolean hotelBDefault = jdbcTemplate.queryForObject("""
                SELECT default_hotel
                FROM platform_user_hotel
                WHERE user_id = ?
                  AND hotel_id = 'M003-REVIEW-HOTEL-B'
                """, Boolean.class, user.getId());

        assertThat(defaultCount).isEqualTo(1);
        assertThat(hotelADefault).isFalse();
        assertThat(hotelBDefault).isTrue();
    }

    @Test
    void shouldRejectMultipleDefaultHotelsAtDatabaseLevel() {
        PlatformUserEntity user = user("m003-review-hotel-db-user");
        identityRepository.insertUser(user);

        jdbcTemplate.update("""
                INSERT INTO platform_user_hotel (id, user_id, hotel_id, default_hotel, created_at)
                VALUES (?, ?, ?, ?, ?)
                """, 9003003001L, user.getId(), "M003-REVIEW-HOTEL-DB-A", true, LocalDateTime.now());

        assertThatThrownBy(() -> jdbcTemplate.update("""
                INSERT INTO platform_user_hotel (id, user_id, hotel_id, default_hotel, created_at)
                VALUES (?, ?, ?, ?, ?)
                """, 9003003002L, user.getId(), "M003-REVIEW-HOTEL-DB-B", true, LocalDateTime.now()))
                .isInstanceOf(DataIntegrityViolationException.class);
    }

    private PlatformUserEntity user(String username) {
        LocalDateTime now = LocalDateTime.now();
        PlatformUserEntity user = new PlatformUserEntity();
        user.setUsername(username);
        user.setPasswordHash("{bcrypt}placeholder");
        user.setDisplayName(username);
        user.setUserStatus(PlatformUserStatus.ACTIVE.name());
        user.setSuperAdmin(false);
        user.setPasswordChangedAt(now);
        user.setCreatedAt(now);
        user.setUpdatedAt(now);
        return user;
    }

    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;
    }
}
