<?php

use Modules\Booking\Enums\BookingStatus;
use Modules\Booking\Models\Booking;
use Modules\Payment\Enums\PaymentStatus;
use Modules\Payment\Events\PaymentCompleted;
use Modules\Payment\Listeners\MarkBookingPaid;
use Modules\Payment\Models\Payment;

test('flips a pending_payment booking to confirmed', function () {
    $booking = Booking::factory()->create(['status' => BookingStatus::PendingPayment]);
    $payment = Payment::factory()->completed()->create(['booking_id' => $booking->id]);

    (new MarkBookingPaid)->handle(new PaymentCompleted($payment));

    expect($booking->refresh()->status)->toBe(BookingStatus::Confirmed);
});

test('does not touch a booking that already moved on for another reason', function () {
    $booking = Booking::factory()->create(['status' => BookingStatus::Cancelled]);
    $payment = Payment::factory()->completed()->create(['booking_id' => $booking->id, 'status' => PaymentStatus::Completed]);

    (new MarkBookingPaid)->handle(new PaymentCompleted($payment));

    expect($booking->refresh()->status)->toBe(BookingStatus::Cancelled);
});

test('does not crash if the booking was soft-deleted before this queued listener ran', function () {
    $booking = Booking::factory()->create(['status' => BookingStatus::PendingPayment]);
    $payment = Payment::factory()->completed()->create(['booking_id' => $booking->id]);
    $booking->delete();

    expect(fn () => (new MarkBookingPaid)->handle(new PaymentCompleted($payment->fresh())))
        ->not->toThrow(Throwable::class);
});

test('a round trip: paying the primary leg also confirms its linked return leg', function () {
    $outbound = Booking::factory()->create(['status' => BookingStatus::PendingPayment]);
    $return = Booking::factory()->create([
        'status' => BookingStatus::PendingPayment,
        'is_return_leg' => true,
        'linked_booking_id' => $outbound->id,
    ]);
    $outbound->update(['linked_booking_id' => $return->id]);

    $payment = Payment::factory()->completed()->create(['booking_id' => $outbound->id]);

    (new MarkBookingPaid)->handle(new PaymentCompleted($payment));

    expect($outbound->refresh()->status)->toBe(BookingStatus::Confirmed)
        ->and($return->refresh()->status)->toBe(BookingStatus::Confirmed);
});
