<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * @return array<int, string>
     */
    private function tenantOwnedTables(): array
    {
        return [
            'policies',
            'policy_versions',
            'backup_sets',
            'backup_items',
            'restore_runs',
            'backup_schedules',
            'inventory_items',
            'inventory_links',
            'entra_groups',
            'findings',
            'entra_role_definitions',
            'managed_environment_permissions',
        ];
    }

    public function up(): void
    {
        $driver = DB::getDriverName();

        if (! in_array($driver, ['pgsql', 'mysql'], true)) {
            return;
        }

        foreach ($this->tenantOwnedTables() as $table) {
            if (! Schema::hasTable($table) || ! Schema::hasColumn($table, 'workspace_id')) {
                continue;
            }

            $missingCount = (int) DB::table($table)
                ->whereNull('workspace_id')
                ->count();

            if ($missingCount > 0) {
                throw new \RuntimeException(sprintf(
                    'Cannot enforce NOT NULL on %s.workspace_id while %d rows are missing a workspace binding.',
                    $table,
                    $missingCount,
                ));
            }

            if ($driver === 'pgsql') {
                DB::statement(sprintf('ALTER TABLE %s ALTER COLUMN workspace_id SET NOT NULL', $table));
            }

            if ($driver === 'mysql') {
                DB::statement(sprintf('ALTER TABLE %s MODIFY workspace_id BIGINT UNSIGNED NOT NULL', $table));
            }
        }
    }

    public function down(): void
    {
        $driver = DB::getDriverName();

        if (! in_array($driver, ['pgsql', 'mysql'], true)) {
            return;
        }

        foreach ($this->tenantOwnedTables() as $table) {
            if (! Schema::hasTable($table) || ! Schema::hasColumn($table, 'workspace_id')) {
                continue;
            }

            if ($driver === 'pgsql') {
                DB::statement(sprintf('ALTER TABLE %s ALTER COLUMN workspace_id DROP NOT NULL', $table));
            }

            if ($driver === 'mysql') {
                DB::statement(sprintf('ALTER TABLE %s MODIFY workspace_id BIGINT UNSIGNED NULL', $table));
            }
        }
    }
};
