<?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
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        $driver = DB::getDriverName();

        Schema::table('tenants', function (Blueprint $table) use ($driver): void {
            $column = $table->foreignId('workspace_id')->nullable();

            if ($driver !== 'sqlite') {
                $column
                    ->after('id')
                    ->constrained('workspaces')
                    ->nullOnDelete();
            }

            $table->index('workspace_id');
        });

        if ($driver === 'sqlite') {
            // SQLite table rebuilds can drop/flatten the partial index defined in
            // 2025_12_11_192942_add_is_current_to_tenants.php. Recreate it here.
            DB::statement('DROP INDEX IF EXISTS tenants_current_unique');
            DB::statement('CREATE UNIQUE INDEX tenants_current_unique ON tenants (is_current) WHERE is_current = 1 AND deleted_at IS NULL');
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('tenants', function (Blueprint $table) {
            $table->dropConstrainedForeignId('workspace_id');
        });
    }
};
