<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('users', function (Blueprint $table) {
            // Add new columns
            $table->string('first_name')->nullable()->after('id');
            $table->string('last_name')->nullable()->after('first_name');

            // Make 'name' nullable so inserts won't fail
            $table->string('name')->nullable()->change();
        });

        // Backfill: split existing 'name' into first and last
        $users = DB::table('users')->select('id', 'name')->get();

        foreach ($users as $user) {
            if (!$user->name) {
                continue;
            }

            // Split the name safely
            $parts = explode(' ', $user->name, 2);
            $first = $parts[0];
            $last = $parts[1] ?? '';

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

    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn(['first_name', 'last_name']);

            // restore name to not null if needed
            $table->string('name')->nullable(false)->change();
        });
    }
};
