<?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 $t) {
            if (! Schema::hasColumn('users', 'invited_at')) {
                $t->timestamp('invited_at')->nullable()->after('status');
            }
            if (! Schema::hasColumn('users', 'invited_by_id')) {
                $t->foreignId('invited_by_id')->nullable()->after('invited_at')->constrained('users')->nullOnDelete();
            }
            if (! Schema::hasColumn('users', 'accepted_at')) {
                $t->timestamp('accepted_at')->nullable()->after('invited_by_id');
            }
            if (! Schema::hasColumn('users', 'invitation_token')) {
                $t->string('invitation_token', 80)->nullable()->after('accepted_at');
            }
        });
        // index on token for fast lookup
        if (Schema::hasColumn('users', 'invitation_token')) {
            try {
                Schema::table('users', function (Blueprint $t) {
                    $t->index('invitation_token', 'users_invitation_token_idx');
                });
            } catch (\Throwable $e) { /* idempotent */ }
        }
    }

    public function down(): void
    {
        Schema::table('users', function (Blueprint $t) {
            try { $t->dropIndex('users_invitation_token_idx'); } catch (\Throwable $e) {}
            foreach (['invitation_token', 'accepted_at', 'invited_by_id', 'invited_at'] as $col) {
                if (Schema::hasColumn('users', $col)) {
                    if ($col === 'invited_by_id') {
                        try { $t->dropForeign(['invited_by_id']); } catch (\Throwable $e) {}
                    }
                    $t->dropColumn($col);
                }
            }
        });
    }
};
