<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        if (! Schema::hasColumn('users', 'password') || $this->passwordIsNullable()) {
            return;
        }

        if (Schema::getConnection()->getDriverName() === 'mysql') {
            DB::statement('ALTER TABLE users MODIFY password VARCHAR(255) NULL');

            return;
        }

        Schema::table('users', function ($table): void {
            $table->string('password')->nullable()->change();
        });
    }

    public function down(): void
    {
        // OAuth-only accounts are allowed to have no password.
    }

    private function passwordIsNullable(): bool
    {
        $passwordColumn = collect(Schema::getColumns('users'))
            ->firstWhere('name', 'password');

        return (bool) ($passwordColumn['nullable'] ?? false);
    }
};
