<?php

use Modules\Booking\Enums\BookingStatus;
use Modules\Booking\Models\Booking;
use Modules\Payment\Enums\PaymentMethod;
use Modules\Payment\Enums\RefundStatus;
use Modules\Payment\Events\RefundProcessed;
use Modules\Payment\Listeners\MarkBookingRefunded;
use Modules\Payment\Models\Payment;
use Modules\Payment\Models\Refund;

test('flips a confirmed booking to cancelled', function () {
    $booking = Booking::factory()->create(['status' => BookingStatus::Confirmed]);
    $payment = Payment::factory()->completed()->create(['booking_id' => $booking->id, 'gateway' => PaymentMethod::KbzMiniApp]);
    $refund = Refund::factory()->create(['payment_id' => $payment->id, 'status' => RefundStatus::Completed]);

    (new MarkBookingRefunded)->handle(new RefundProcessed($refund));

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

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, 'gateway' => PaymentMethod::KbzMiniApp]);
    $refund = Refund::factory()->create(['payment_id' => $payment->id, 'status' => RefundStatus::Completed]);

    (new MarkBookingRefunded)->handle(new RefundProcessed($refund));

    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::Confirmed]);
    $payment = Payment::factory()->completed()->create(['booking_id' => $booking->id, 'gateway' => PaymentMethod::KbzMiniApp]);
    $refund = Refund::factory()->create(['payment_id' => $payment->id, 'status' => RefundStatus::Completed]);
    $booking->delete();

    expect(fn () => (new MarkBookingRefunded)->handle(new RefundProcessed($refund->fresh())))
        ->not->toThrow(Throwable::class);
});
