package org.raddatz.familienarchiv.user;

import org.junit.jupiter.api.Test;
import org.raddatz.familienarchiv.PostgresContainerConfig;
import org.raddatz.familienarchiv.config.FlywayConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;
import org.springframework.boot.jdbc.test.autoconfigure.AutoConfigureTestDatabase;
import org.springframework.context.annotation.Import;
import org.springframework.jdbc.core.JdbcTemplate;

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

/**
 * Verifies the V60 rename: {@code users → app_users} and the three literal
 * {@code user_id} FK columns. Semantic FK columns (e.g. {@code audit_log.actor_id})
 * are deliberately untouched and asserted to remain. See issue #418.
 */
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Import({PostgresContainerConfig.class, FlywayConfig.class})
class RenameUsersToAppUsersMigrationTest {

    @Autowired JdbcTemplate jdbc;

    @Test
    void v60_appUsersTableExists_andUsersTableIsGone() {
        assertThat(tableExists("app_users")).isTrue();
        assertThat(tableExists("users")).isFalse();
    }

    @Test
    void v60_appUsersGroupsJoinTableExists_withRenamedColumn() {
        assertThat(tableExists("app_users_groups")).isTrue();
        assertThat(tableExists("users_groups")).isFalse();
        assertThat(columnExists("app_users_groups", "app_user_id")).isTrue();
        assertThat(columnExists("app_users_groups", "user_id")).isFalse();
    }

    @Test
    void v60_commentMentionsColumnRenamed() {
        assertThat(columnExists("comment_mentions", "app_user_id")).isTrue();
        assertThat(columnExists("comment_mentions", "user_id")).isFalse();
    }

    @Test
    void v60_passwordResetTokensColumnRenamed() {
        assertThat(columnExists("password_reset_tokens", "app_user_id")).isTrue();
        assertThat(columnExists("password_reset_tokens", "user_id")).isFalse();
    }

    @Test
    void v60_auditLogActorIdRemains() {
        assertThat(columnExists("audit_log", "actor_id")).isTrue();
        assertThat(columnExists("audit_log", "app_user_id")).isFalse();
    }

    private boolean tableExists(String tableName) {
        Integer count = jdbc.queryForObject(
                "SELECT COUNT(*) FROM information_schema.tables " +
                        "WHERE table_schema = 'public' AND table_name = ?",
                Integer.class, tableName);
        return count != null && count > 0;
    }

    private boolean columnExists(String tableName, String columnName) {
        Integer count = jdbc.queryForObject(
                "SELECT COUNT(*) FROM information_schema.columns " +
                        "WHERE table_schema = 'public' AND table_name = ? AND column_name = ?",
                Integer.class, tableName, columnName);
        return count != null && count > 0;
    }
}
