<?php

namespace Modules\Payment\Listeners;

use Illuminate\Contracts\Queue\ShouldQueue;
use Modules\Booking\Enums\BookingStatus;
use Modules\Payment\Events\RefundProcessed;

/**
 * Flips the Booking to cancelled once a Refund against one of its Payments
 * completes (domain.md §5). Guarded the same way as MarkBookingPaid — only
 * ever moves a still-confirmed booking, never clobbers one that moved on
 * for another reason.
 */
class MarkBookingRefunded implements ShouldQueue
{
    public function handle(RefundProcessed $event): void
    {
        // The leg actually refunded — not payment->booking, since a round
        // trip's return leg refunds against the primary leg's shared
        // Payment (domain.md §2b). Falls back to payment->booking for
        // pre-redesign rows where booking_id wasn't yet recorded.
        $booking = $event->refund->booking ?? $event->refund->payment->booking;

        // Booking uses SoftDeletes — normally unreachable here (a confirmed
        // booking is never deletable, BookingPolicy::delete), but this
        // listener is queued, so it's worth guarding against a booking that
        // vanished between dispatch and execution regardless.
        if ($booking === null) {
            return;
        }

        if ($booking->status === BookingStatus::Confirmed) {
            $booking->update(['status' => BookingStatus::Cancelled]);
        }
    }
}
