<?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
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // First, update any null technician_id values (if any exist)
        // Assign them to the first available technician
        $firstTechnician = DB::table('technicians')->first();
        if ($firstTechnician) {
            DB::table('orders')
                ->whereNull('technician_id')
                ->update(['technician_id' => $firstTechnician->id]);
        }
        
        Schema::table('orders', function (Blueprint $table) {
            // Drop the foreign key constraint first
            $table->dropForeign(['technician_id']);
        });

        Schema::table('orders', function (Blueprint $table) {
            // Make technician_id not nullable
            $table->foreignId('technician_id')->nullable(false)->change();
            
            // Re-add the foreign key constraint with restrict delete
            $table->foreign('technician_id')->references('id')->on('technicians')->onDelete('restrict');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('orders', function (Blueprint $table) {
            // Drop the foreign key constraint
            $table->dropForeign(['technician_id']);
        });

        Schema::table('orders', function (Blueprint $table) {
            // Make technician_id nullable again
            $table->foreignId('technician_id')->nullable()->change();
            
            // Re-add the foreign key constraint with set null
            $table->foreign('technician_id')->references('id')->on('technicians')->onDelete('set null');
        });
    }
};
