<?php

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

return new class extends Migration
{
    /**
     * A round trip's Payment is combined on the primary (outbound) leg
     * (domain.md §2b), so `refund->payment->booking` is no longer reliable
     * for identifying which leg a refund actually cancels — a refund
     * against the return leg still hangs off the primary's Payment.
     * `booking_id` records the actual leg RefundBookingAction was asked to
     * refund, so MarkBookingRefunded flips the right booking to cancelled.
     */
    public function up(): void
    {
        Schema::table('refunds', function (Blueprint $table) {
            $table->foreignId('booking_id')->nullable()->after('payment_id')
                ->constrained('bookings')->nullOnDelete();
        });

        // Backfill existing rows from their Payment's booking — correct for
        // every pre-existing refund, since round trip didn't exist yet.
        DB::statement(
            'update refunds set booking_id = payments.booking_id '.
            'from payments where payments.id = refunds.payment_id'
        );
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('refunds', function (Blueprint $table) {
            $table->dropConstrainedForeignId('booking_id');
        });
    }
};
