<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
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 $tableName) {
            if (! Schema::hasTable($tableName) || ! Schema::hasColumn($tableName, 'workspace_id')) {
                continue;
            }

            $workspaceConstraint = sprintf('%s_workspace_fk', $tableName);
            $tenantWorkspaceConstraint = sprintf('%s_environment_workspace_fk', $tableName);

            Schema::table($tableName, function (Blueprint $table) use ($workspaceConstraint, $tenantWorkspaceConstraint): void {
                $table->foreign('workspace_id', $workspaceConstraint)
                    ->references('id')
                    ->on('workspaces')
                    ->cascadeOnDelete();

                $table->foreign(['managed_environment_id', 'workspace_id'], $tenantWorkspaceConstraint)
                    ->references(['id', 'workspace_id'])
                    ->on('managed_environments')
                    ->cascadeOnDelete();
            });
        }
    }

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

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

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

            $workspaceConstraint = sprintf('%s_workspace_fk', $tableName);
            $tenantWorkspaceConstraint = sprintf('%s_environment_workspace_fk', $tableName);

            Schema::table($tableName, function (Blueprint $table) use ($workspaceConstraint, $tenantWorkspaceConstraint): void {
                $table->dropForeign($tenantWorkspaceConstraint);
                $table->dropForeign($workspaceConstraint);
            });
        }
    }
};
