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 java.util.List;
import java.util.Map;

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

class V4DeploymentCreatedByMigrationIT extends AbstractPostgresIT {

    @Autowired JdbcTemplate jdbc;

    @Test
    void created_by_column_exists_with_correct_type_and_nullable() {
        // Scope to current schema — Testcontainers reuse can otherwise leave
        // a previous run's tenant_default schema visible alongside public.
        List<Map<String, Object>> cols = jdbc.queryForList(
            "SELECT column_name, data_type, is_nullable " +
            "FROM information_schema.columns " +
            "WHERE table_name = 'deployments' AND column_name = 'created_by' " +
            "  AND table_schema = current_schema()"
        );
        assertThat(cols).hasSize(1);
        assertThat(cols.get(0)).containsEntry("data_type", "text");
        assertThat(cols.get(0)).containsEntry("is_nullable", "YES");
    }

    @Test
    void created_by_index_exists() {
        Integer count = jdbc.queryForObject(
            "SELECT count(*)::int FROM pg_indexes " +
            "WHERE tablename = 'deployments' AND indexname = 'idx_deployments_created_by' " +
            "  AND schemaname = current_schema()",
            Integer.class
        );
        assertThat(count).isEqualTo(1);
    }

    @Test
    void created_by_has_fk_to_users() {
        Integer count = jdbc.queryForObject(
            "SELECT count(*)::int FROM information_schema.table_constraints tc " +
            "JOIN information_schema.constraint_column_usage ccu " +
            "  ON tc.constraint_name = ccu.constraint_name " +
            "WHERE tc.table_name = 'deployments' " +
            "  AND tc.constraint_type = 'FOREIGN KEY' " +
            "  AND ccu.table_name = 'users' " +
            "  AND ccu.column_name = 'user_id' " +
            "  AND tc.table_schema = current_schema()",
            Integer.class
        );
        assertThat(count).isGreaterThanOrEqualTo(1);
    }
}
