<?php

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

return new class extends Migration
{
    public function up(): void
    {
        // Guard: table might not exist yet in some environments
        if (! Schema::hasTable('jobs')) {
            return;
        }

        // Guard: don't try to add it if it already exists (dev/staging)
        if (Schema::hasColumn('jobs', 'vehicle_id')) {
            return;
        }

        Schema::table('jobs', function (Blueprint $table) {
            // If brand_id exists, nice to keep them together.
            if (Schema::hasColumn('jobs', 'brand_id')) {
                $table->unsignedBigInteger('vehicle_id')
                    ->nullable()
                    ->after('brand_id');
            } else {
                // Fallback: just add it at the end; column order doesn't really matter
                $table->unsignedBigInteger('vehicle_id')
                    ->nullable();
            }
        });
    }

    public function down(): void
    {
        if (! Schema::hasTable('jobs')) {
            return;
        }

        if (! Schema::hasColumn('jobs', 'vehicle_id')) {
            return;
        }

        Schema::table('jobs', function (Blueprint $table) {
            $table->dropColumn('vehicle_id');
        });
    }
};
