<?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
    {
        $secureTokenAlreadyExists = Schema::hasColumn('bookings', 'secure_token');

        Schema::table('bookings', function (Blueprint $table) use ($secureTokenAlreadyExists): void {
            if (! $secureTokenAlreadyExists) {
                $table->string('secure_token', 100)->nullable()->after('booking_number')->unique();
            }
            if (! Schema::hasColumn('bookings', 'guest_documents_received')) {
                $table->boolean('guest_documents_received')->default(false)->after('prepayment_received');
            }
            if (! Schema::hasColumn('bookings', 'guest_documents_consent_at')) {
                $table->dateTime('guest_documents_consent_at')->nullable()->after('guest_documents_received');
            }
        });

        if (! $secureTokenAlreadyExists) {
            \Illuminate\Support\Facades\DB::table('bookings')
                ->whereNull('secure_token')
                ->orderBy('id')
                ->select(['id'])
                ->chunkById(100, function ($bookings): void {
                    foreach ($bookings as $booking) {
                        \Illuminate\Support\Facades\DB::table('bookings')
                            ->where('id', $booking->id)
                            ->update(['secure_token' => \Illuminate\Support\Str::random(64)]);
                    }
                });
        }
    }

    public function down(): void
    {
        $secureTokenAlreadyExists = Schema::hasColumn('bookings', 'secure_token');

        Schema::table('bookings', function (Blueprint $table) use ($secureTokenAlreadyExists): void {
            foreach (['guest_documents_consent_at', 'guest_documents_received', 'secure_token'] as $column) {
                if (Schema::hasColumn('bookings', $column)) {
                    $table->dropColumn($column);
                }
            }
        });
    }
};
