<?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('users')) {
            return;
        }

        Schema::table('users', function (Blueprint $table): void {
            if (! Schema::hasColumn('users', 'admin_failed_attempts')) {
                $table->unsignedInteger('admin_failed_attempts')->default(0)->after('showpassword');
            }

            if (! Schema::hasColumn('users', 'admin_is_locked')) {
                $table->boolean('admin_is_locked')->default(false)->after('admin_failed_attempts');
            }

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

    public function down(): void
    {
        if (! Schema::hasTable('users')) {
            return;
        }

        Schema::table('users', function (Blueprint $table): void {
            $dropColumns = [];

            foreach (['admin_failed_attempts', 'admin_is_locked', 'admin_locked_at'] as $column) {
                if (Schema::hasColumn('users', $column)) {
                    $dropColumns[] = $column;
                }
            }

            if ($dropColumns !== []) {
                $table->dropColumn($dropColumns);
            }
        });
    }
};
