<?php

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

return new class extends Migration
{
    public function up(): void
    {
        if (! Schema::hasTable('events')) return;
        Schema::table('events', function (Blueprint $table) {
            if (! Schema::hasColumn('events', 'tenant_id')) {
                $table->foreignId('tenant_id')->nullable()->after('id')->constrained('tenants')->nullOnDelete();
            }
            if (Schema::hasColumn('events', 'slug')) {
                // Optional: ensure index exists
                try { $table->index('slug'); } catch (\Throwable $e) {}
            }
        });
    }

    public function down(): void
    {
        if (! Schema::hasTable('events')) return;
        Schema::table('events', function (Blueprint $table) {
            if (Schema::hasColumn('events', 'tenant_id')) {
                try { $table->dropConstrainedForeignId('tenant_id'); } catch (\Throwable $e) {
                    try { $table->dropForeign(['tenant_id']); } catch (\Throwable $e2) {}
                    $table->dropColumn('tenant_id');
                }
            }
        });
    }
};

