<?php

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

/**
 * Reworks the assignment/response workflow: what used to be called
 * "Pending" (a brand-new booking with no driver yet) is renamed
 * "Unassigned", and what used to be called "Assigned" (a driver has been
 * given the job but hasn't responded yet) is renamed "Pending" — matching
 * the new spec's naming exactly. Order matters: renaming the no-driver
 * state out of the way first means the second rename can't collide with it.
 * "Rejected" is new — a driver explicitly declining a job, logged as its
 * own status-history entry immediately before the booking is bounced back
 * to Unassigned for reassignment.
 */
return new class extends Migration
{
    public function up(): void
    {
        DB::table('booking_statuses')->where('name', 'Pending')->update(['name' => 'Unassigned']);
        DB::table('booking_statuses')->where('name', 'Assigned')->update(['name' => 'Pending']);

        if (! DB::table('booking_statuses')->where('name', 'Rejected')->exists()) {
            DB::table('booking_statuses')->insert([
                'name' => 'Rejected',
                // Sits right after Pending in the flow (a driver can only
                // reject from Pending), pushing every later status's
                // sort_order up by one so ordering stays contiguous.
                'sort_order' => 3,
                'created_at' => now(),
                'updated_at' => now(),
            ]);

            DB::table('booking_statuses')
                ->whereNotIn('name', ['Unassigned', 'Pending', 'Rejected'])
                ->orderBy('sort_order')
                ->get(['id', 'sort_order'])
                ->values()
                ->each(fn ($status, $i) => DB::table('booking_statuses')
                    ->where('id', $status->id)
                    ->update(['sort_order' => $i + 4]));
        }
    }

    public function down(): void
    {
        DB::table('booking_statuses')->where('name', 'Rejected')->delete();
        DB::table('booking_statuses')->where('name', 'Pending')->update(['name' => 'Assigned']);
        DB::table('booking_statuses')->where('name', 'Unassigned')->update(['name' => 'Pending']);
    }
};
