<?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
    {
        if (! Schema::hasTable('bookings')) {
            return;
        }

        Schema::table('bookings', function (Blueprint $t) {
            if (! Schema::hasColumn('bookings', 'external_reference')) {
                $t->string('external_reference')->nullable()->index();
            }

            if (! Schema::hasColumn('bookings', 'customer_id')) {
                $t->foreignId('customer_id')->nullable()->constrained()->nullOnDelete();
            }

            if (! Schema::hasColumn('bookings', 'pickup_at')) {
                $t->dateTime('pickup_at')->nullable();
            }

            if (! Schema::hasColumn('bookings', 'return_at')) {
                $t->dateTime('return_at')->nullable();
            }

            if (! Schema::hasColumn('bookings', 'vehicle_name')) {
                $t->string('vehicle_name')->nullable();
            }

            if (! Schema::hasColumn('bookings', 'total_amount')) {
                $t->integer('total_amount')->nullable(); // cents
            }

            if (! Schema::hasColumn('bookings', 'currency')) {
                $t->string('currency', 3)->nullable();
            }
        });
    }

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

        // Drop FK first where applicable, then columns (guarded for idempotency)
        $driver = Schema::getConnection()->getDriverName();

        Schema::table('bookings', function (Blueprint $t) use ($driver) {
            if (Schema::hasColumn('bookings', 'customer_id')) {
                // Only drop the FK on non-sqlite
                if ($driver !== 'sqlite') {
                    // default name when using ->constrained(): bookings_customer_id_foreign
                    $t->dropForeign('bookings_customer_id_foreign');
                }
                $t->dropColumn('customer_id');
            }

            if (Schema::hasColumn('bookings', 'external_reference')) {
                // index will be dropped automatically with the column
                $t->dropColumn('external_reference');
            }

            if (Schema::hasColumn('bookings', 'pickup_at')) {
                $t->dropColumn('pickup_at');
            }

            if (Schema::hasColumn('bookings', 'return_at')) {
                $t->dropColumn('return_at');
            }

            if (Schema::hasColumn('bookings', 'vehicle_name')) {
                $t->dropColumn('vehicle_name');
            }

            if (Schema::hasColumn('bookings', 'total_amount')) {
                $t->dropColumn('total_amount');
            }

            if (Schema::hasColumn('bookings', 'currency')) {
                $t->dropColumn('currency');
            }
        });
    }
};
