<?php

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

return new class extends Migration {
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // Add missing columns used by bagging flows without altering existing ones
        if (!Schema::hasColumn('bags', 'bag_number') || !Schema::hasColumn('bags', 'status') || !Schema::hasColumn('bags', 'rider_id')) {
            Schema::table('bags', function (Blueprint $table) {
                if (!Schema::hasColumn('bags', 'bag_number')) {
                    $table->string('bag_number')->unique();
                }
                if (!Schema::hasColumn('bags', 'status')) {
                    $table->string('status')->default('open');
                }
                if (!Schema::hasColumn('bags', 'rider_id')) {
                    $table->unsignedBigInteger('rider_id')->nullable()->index();
                }
            });
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // Remove columns only if they exist
        if (Schema::hasColumn('bags', 'bag_number')) {
            Schema::table('bags', function (Blueprint $table) {
                $table->dropColumn('bag_number');
            });
        }
        if (Schema::hasColumn('bags', 'status')) {
            Schema::table('bags', function (Blueprint $table) {
                $table->dropColumn('status');
            });
        }
        if (Schema::hasColumn('bags', 'rider_id')) {
            Schema::table('bags', function (Blueprint $table) {
                $table->dropColumn('rider_id');
            });
        }
    }
};