<?php

use Illuminate\Support\Facades\DB;

it('enforces workspace_id foreign keys on tenant-owned tables', function () {
    if (DB::getDriverName() !== 'pgsql') {
        $this->markTestSkipped('Postgres-only: validates FK constraints via pg_constraint.');
    }

    $tables = [
        'policies',
        'policy_versions',
        'backup_sets',
        'backup_items',
        'restore_runs',
        'backup_schedules',
        'inventory_items',
        'inventory_links',
        'entra_groups',
        'findings',
        'entra_role_definitions',
        'managed_environment_permissions',
    ];

    foreach ($tables as $table) {
        $sql = <<<'SQL'
                        SELECT c.conname, c.convalidated
                        FROM pg_constraint c
                        JOIN pg_class rel ON rel.oid = c.conrelid
                        JOIN pg_class ref ON ref.oid = c.confrelid
                        JOIN pg_attribute att ON att.attrelid = rel.oid AND att.attnum = ANY(c.conkey)
                        WHERE c.contype = 'f'
                            AND rel.relname = ?
                            AND ref.relname = 'workspaces'
                            AND att.attname = 'workspace_id'
                        SQL;

        $constraints = DB::select(
            $sql,
            [$table],
        );

        expect($constraints)->not->toBeEmpty();

        $allValidated = collect($constraints)->every(fn ($c): bool => (bool) $c->convalidated);
        expect($allValidated)->toBeTrue();
    }
});
