<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('first_name')->nullable()->after('name');
            $table->string('last_name')->nullable()->after('first_name');
            $table->string('username')->nullable()->unique()->after('last_name');
            $table->string('website')->nullable()->after('username');
        });

        // Backfill existing rows so nobody lands on the profile page with
        // empty required-looking fields: split the current `name` on the
        // first space, and default `username` to the email's local part.
        foreach (DB::table('users')->select('id', 'name', 'email')->get() as $user) {
            $parts     = preg_split('/\s+/', trim($user->name), 2);
            $firstName = $parts[0] ?? '';
            $lastName  = $parts[1] ?? '';

            $baseUsername = strtolower(explode('@', $user->email)[0]);
            $username     = $baseUsername;
            $suffix       = 1;
            while (DB::table('users')->where('username', $username)->where('id', '!=', $user->id)->exists()) {
                $username = $baseUsername . $suffix;
                $suffix++;
            }

            DB::table('users')->where('id', $user->id)->update([
                'first_name' => $firstName,
                'last_name'  => $lastName,
                'username'   => $username,
            ]);
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn(['first_name', 'last_name', 'username', 'website']);
        });
    }
};
