<?php

namespace Modules\Payment\Listeners;

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

/**
 * Flips the Booking to confirmed once its Payment is confirmed successful
 * (domain.md §5). Queued — ConfirmPaymentAction's own idempotency check is
 * what actually prevents this firing twice for the same Payment; the guard
 * here is just to never clobber a booking that moved on for another reason.
 */
class MarkBookingPaid implements ShouldQueue
{
    public function handle(PaymentCompleted $event): void
    {
        $booking = $event->payment->booking;

        // Booking uses SoftDeletes — normally unreachable here (a
        // pending_payment 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::PendingPayment) {
            $booking->update(['status' => BookingStatus::Confirmed]);
        }

        // Round trip: payment is combined on the outbound leg, so its
        // success also confirms the linked return leg — the return leg
        // never gets its own Payment (domain.md §2b).
        $linkedBooking = $booking->linkedBooking;

        if ($linkedBooking !== null && $linkedBooking->status === BookingStatus::PendingPayment) {
            $linkedBooking->update(['status' => BookingStatus::Confirmed]);
        }
    }
}
