<?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
    {
        Schema::table('reservations', function (Blueprint $table) {
            $table->dropForeign(['user_id']);
        });

        Schema::table('reservations', function (Blueprint $table) {
            $table->unsignedBigInteger('user_id')->nullable()->change();
        });

        Schema::table('reservations', function (Blueprint $table) {
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });

        Schema::table('reservations', function (Blueprint $table) {
            $table->string('guest_phone_normalized', 32)->nullable()->after('user_id');
            $table->string('guest_phone_raw', 32)->nullable()->after('guest_phone_normalized');
            $table->string('guest_name', 255)->nullable()->after('guest_phone_raw');
            $table->string('source', 32)->default('app')->after('guest_name');
            $table->foreignId('created_by_owner_id')->nullable()->after('source')
                ->constrained('users')->nullOnDelete();
            $table->timestamp('sms_sent_at')->nullable()->after('created_by_owner_id');
            $table->index('guest_phone_normalized');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('reservations', function (Blueprint $table) {
            $table->dropIndex(['guest_phone_normalized']);
            $table->dropForeign(['created_by_owner_id']);
            $table->dropColumn([
                'guest_phone_normalized',
                'guest_phone_raw',
                'guest_name',
                'source',
                'created_by_owner_id',
                'sms_sent_at',
            ]);
        });

        Schema::table('reservations', function (Blueprint $table) {
            $table->dropForeign(['user_id']);
        });

        Schema::table('reservations', function (Blueprint $table) {
            $table->unsignedBigInteger('user_id')->nullable(false)->change();
        });

        Schema::table('reservations', function (Blueprint $table) {
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });
    }
};
