<?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', 'email_verified_at')) {
                $table->timestamp('email_verified_at')->nullable()->after('email');
            }

            if (! Schema::hasColumn('users', 'onboarding_step')) {
                $table->enum('onboarding_step', ['email', 'verified', 'password', 'username', 'complete'])
                    ->nullable()
                    ->after('email_verified_at');
            }

            if (! Schema::hasColumn('users', 'username_changed_at')) {
                $table->timestamp('username_changed_at')->nullable()->after('username');
            }
        });

        if (! Schema::hasTable('user_verification_tokens')) {
            Schema::create('user_verification_tokens', function (Blueprint $table) {
                $table->id();
                $table->foreignId('user_id')->constrained('users')->cascadeOnDelete();
                $table->string('token', 128)->unique();
                $table->timestamp('expires_at');
                $table->timestamps();

                $table->index(['user_id', 'expires_at']);
            });
        }
    }

    public function down(): void
    {
        if (Schema::hasTable('user_verification_tokens')) {
            Schema::drop('user_verification_tokens');
        }

        Schema::table('users', function (Blueprint $table) {
            if (Schema::hasColumn('users', 'onboarding_step')) {
                $table->dropColumn('onboarding_step');
            }
        });
    }
};
