<?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
    {
        // Drop in reverse dependency order
        if (Schema::hasTable('bookings')) {
            Schema::drop('bookings');
        }
        if (Schema::hasTable('payments')) {
            Schema::drop('payments');
        }

        // Recreate payments
        Schema::create('payments', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('account_id')->constrained()->cascadeOnDelete();
            $table->bigInteger('amount_cents');
            $table->string('currency', 3)->default('EUR');
            $table->string('reference')->nullable();
            $table->timestamp('paid_at')->nullable();
            $table->jsonb('meta')->nullable();
            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();
            $table->softDeletes();

            $table->index(['account_id', 'paid_at']);
            $table->index('reference');
        });

        // Recreate bookings
        Schema::create('bookings', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('account_id')->constrained()->cascadeOnDelete();
            $table->foreignId('payment_id')->nullable()->constrained('payments')->nullOnDelete();
            $table->bigInteger('amount_cents');
            $table->enum('type', ['debit', 'credit']);
            $table->string('description')->nullable();
            $table->timestamp('booked_at')->nullable();
            $table->timestamps();
            $table->softDeletes();

            $table->index(['account_id', 'booked_at']);
        });
    }

    public function down(): void
    {
        if (Schema::hasTable('bookings')) {
            Schema::drop('bookings');
        }
        if (Schema::hasTable('payments')) {
            Schema::drop('payments');
        }
    }
};
