<?php

use App\Models\Tenant\WorkOrder;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('work_orders', function (Blueprint $t) {
            $t->dateTime('eta_at')->nullable()->after('closed_at');
            $t->string('tracking_token', 32)->nullable()->after('eta_at');
            $t->unique('tracking_token');
        });

        WorkOrder::withoutGlobalScopes()
            ->whereNull('tracking_token')
            ->cursor()
            ->each(function (WorkOrder $wo) {
                $wo->tracking_token = Str::random(24);
                $wo->saveQuietly();
            });
    }

    public function down(): void
    {
        Schema::table('work_orders', function (Blueprint $t) {
            $t->dropUnique(['tracking_token']);
            $t->dropColumn(['eta_at', 'tracking_token']);
        });
    }
};
