package com.cameleer.server.app.storage;

import com.cameleer.server.app.AbstractPostgresIT;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

import static org.junit.jupiter.api.Assertions.*;

class FlywayMigrationIT extends AbstractPostgresIT {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Test
    void allMigrationsApplySuccessfully() {
        // Tables-exist check: queryForObject on COUNT(*) throws SQLException on a
        // missing relation, so a successful call IS the existence assertion. The
        // seed-only tables (roles/groups) assert the V1 baseline numbers exactly;
        // the other tables accumulate state from prior tests in the shared
        // Testcontainers Postgres, so we only assert "table exists & COUNT is
        // a non-negative integer" rather than coupling to other ITs' write state.

        Integer userCount = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM users", Integer.class);
        assertTrue(userCount != null && userCount >= 0);

        Integer roleCount = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM roles", Integer.class);
        assertEquals(4, roleCount); // AGENT, VIEWER, OPERATOR, ADMIN — seeded in V1

        Integer groupCount = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM groups", Integer.class);
        assertEquals(1, groupCount); // Admins — seeded in V1

        Integer configCount = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM server_config", Integer.class);
        assertTrue(configCount != null && configCount >= 0);

        Integer auditCount = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM audit_log", Integer.class);
        assertTrue(auditCount != null && auditCount >= 0);

        Integer appConfigCount = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM application_config", Integer.class);
        assertTrue(appConfigCount != null && appConfigCount >= 0);

        Integer appSettingsCount = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM app_settings", Integer.class);
        assertTrue(appSettingsCount != null && appSettingsCount >= 0);
    }
}
