<?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) {
            // Add username (nullable for legacy), unique
            if (!Schema::hasColumn('users', 'username')) {
                $table->string('username', 80)->nullable()->unique()->after('id');
            }

            // Ensure name exists and is nullable
            if (!Schema::hasColumn('users', 'name')) {
                $table->string('name')->nullable();
            } else {
                $table->string('name')->nullable()->change();
            }

            // Email nullable to allow legacy nulls/dupes handling in import
            if (Schema::hasColumn('users', 'email')) {
                $table->string('email')->nullable()->change();
            }

            if (!Schema::hasColumn('users', 'is_active')) {
                $table->boolean('is_active')->default(true)->after('remember_token');
            }

            if (!Schema::hasColumn('users', 'needs_password_reset')) {
                $table->boolean('needs_password_reset')->default(true)->after('is_active');
            }

            if (!Schema::hasColumn('users', 'role')) {
                $table->string('role', 32)->default('user')->after('needs_password_reset');
            }

            if (!Schema::hasColumn('users', 'legacy_password_algo')) {
                $table->string('legacy_password_algo', 32)->nullable()->after('role');
            }

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

            // Soft deletes for user accounts
            if (!Schema::hasColumn('users', 'deleted_at')) {
                $table->softDeletes()->after('last_visit_at');
            }
        });
    }

    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            if (Schema::hasColumn('users', 'username')) $table->dropColumn('username');
            if (Schema::hasColumn('users', 'is_active')) $table->dropColumn('is_active');
            if (Schema::hasColumn('users', 'needs_password_reset')) $table->dropColumn('needs_password_reset');
            if (Schema::hasColumn('users', 'role')) $table->dropColumn('role');
            if (Schema::hasColumn('users', 'legacy_password_algo')) $table->dropColumn('legacy_password_algo');
            if (Schema::hasColumn('users', 'last_visit_at')) $table->dropColumn('last_visit_at');
            if (Schema::hasColumn('users', 'deleted_at')) $table->dropColumn('deleted_at');
        });
    }
};
