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

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

import cn.nianxx.thhotel.ThHotelApplication;
import cn.nianxx.thhotel.platform.identity.common.enums.PlatformUserStatus;
import cn.nianxx.thhotel.platform.identity.domain.PlatformUserEntity;
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.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ActiveProfiles;

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

    @Autowired
    private PlatformIdentityRepository identityRepository;

    @Autowired
    private JdbcTemplate jdbcTemplate;

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

    @Test
    void shouldOnlyCountActiveSuperAdminUsers() {
        long baseline = identityRepository.countSuperAdminUsers();
        identityRepository.insertUser(user("m003-review-disabled-super-admin", PlatformUserStatus.DISABLED.name(), true));

        assertThat(identityRepository.countSuperAdminUsers()).isEqualTo(baseline);

        identityRepository.insertUser(user("m003-review-active-super-admin", PlatformUserStatus.ACTIVE.name(), true));

        assertThat(identityRepository.countSuperAdminUsers()).isEqualTo(baseline + 1);
    }

    private PlatformUserEntity user(String username, String status, boolean superAdmin) {
        LocalDateTime now = LocalDateTime.now();
        PlatformUserEntity user = new PlatformUserEntity();
        user.setUsername(username);
        user.setPasswordHash("{bcrypt}placeholder");
        user.setDisplayName(username);
        user.setUserStatus(status);
        user.setSuperAdmin(superAdmin);
        user.setPasswordChangedAt(now);
        user.setCreatedAt(now);
        user.setUpdatedAt(now);
        return user;
    }
}
