<?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
    {
        Schema::table('users', function (Blueprint $table) {
            if (! Schema::hasColumn('users', 'tenant_id')) {
                $table->foreignId('tenant_id')->nullable()->after('id')
                    ->constrained('tenants')->nullOnDelete();
            }
            if (! Schema::hasColumn('users', 'role')) {
                $table->string('role', 32)->default('tenant_user')->after('password')->index();
            }
        });
    }

    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            if (Schema::hasColumn('users', 'tenant_id')) {
                // Drop FK first if the driver supports it
                try { $table->dropConstrainedForeignId('tenant_id'); } catch (\Throwable $e) {
                    try { $table->dropForeign(['tenant_id']); } catch (\Throwable $e2) {}
                    $table->dropColumn('tenant_id');
                }
            }
            if (Schema::hasColumn('users', 'role')) {
                $table->dropColumn('role');
            }
        });
    }
};

