<?php

use App\Models\User;
use Livewire\Livewire;
use Modules\Booking\Enums\BookingStatus;
use Modules\Booking\Filament\Resources\Bookings\Pages\ListBookings;
use Modules\Booking\Filament\Resources\Bookings\Pages\ViewBooking;
use Modules\Booking\Models\Booking;
use Modules\Booking\Models\BookingVehicleOption;
use Modules\Payment\Contracts\PaymentGatewayInterface;
use Modules\Payment\Data\PaymentRequestData;
use Modules\Payment\Data\PaymentResultData;
use Modules\Payment\Data\RefundResultData;
use Modules\Payment\Enums\PaymentMethod;
use Modules\Payment\Enums\PaymentStatus;
use Modules\Payment\Enums\RefundStatus;
use Modules\Payment\Factories\PaymentGatewayFactory;
use Modules\Payment\Models\Payment;
use Modules\Payment\Models\Refund;
use Modules\Shared\Enums\VehicleOption;
use Spatie\Permission\Models\Permission;

/**
 * Never calls the real KBZ refund API in tests (mirrors RefundResourceTest's
 * fake for the Refunds resource's own process action).
 */
class FakeBookingResourceRefundGateway implements PaymentGatewayInterface
{
    public function initiate(PaymentRequestData $data): PaymentResultData
    {
        throw new RuntimeException('not needed for this test');
    }

    public function verify(string $gatewayTransactionId): PaymentResultData
    {
        throw new RuntimeException('not needed for this test');
    }

    public function refund(string $gatewayTransactionId, string $amount, string $reason): RefundResultData
    {
        return new RefundResultData(status: RefundStatus::Completed, gatewayRefundId: 'REFUND123', gatewayPayload: []);
    }

    public function handleWebhook(array $payload): PaymentResultData
    {
        throw new RuntimeException('not needed for this test');
    }
}

beforeEach(function () {
    foreach (['view_bookings', 'manage_bookings', 'process_refunds'] as $permission) {
        Permission::findOrCreate($permission, 'web');
    }

    $this->admin = User::factory()->create()->givePermissionTo(['view_bookings', 'manage_bookings', 'process_refunds']);
    $this->actingAs($this->admin);
});

test('can list bookings', function () {
    $bookings = Booking::factory()->count(3)->create();

    Livewire::test(ListBookings::class)
        ->assertOk()
        ->assertCanSeeTableRecords($bookings);
});

test('can filter bookings by status', function () {
    $pending = Booking::factory()->create(['status' => BookingStatus::PendingPayment]);
    $confirmed = Booking::factory()->create(['status' => BookingStatus::Confirmed]);

    Livewire::test(ListBookings::class)
        ->filterTable('status', BookingStatus::PendingPayment->value)
        ->assertCanSeeTableRecords([$pending])
        ->assertCanNotSeeTableRecords([$confirmed]);
});

test('the cancel action is visible and enabled for a pending_payment booking', function () {
    $booking = Booking::factory()->create(['status' => BookingStatus::PendingPayment]);

    Livewire::test(ListBookings::class)
        ->assertTableActionVisible('cancel', $booking)
        ->assertTableActionEnabled('cancel', $booking);
});

test('the cancel action is visible but disabled for a confirmed booking', function () {
    $booking = Booking::factory()->create(['status' => BookingStatus::Confirmed]);

    Livewire::test(ListBookings::class)
        ->assertTableActionVisible('cancel', $booking)
        ->assertTableActionDisabled('cancel', $booking);
});

test('the cancel action is hidden from a user without manage_bookings and not the owner', function () {
    $stranger = User::factory()->create();
    $this->actingAs($stranger);

    $booking = Booking::factory()->create(['user_id' => User::factory()->create()->id, 'status' => BookingStatus::PendingPayment]);

    Livewire::test(ListBookings::class)
        ->assertTableActionHidden('cancel', $booking);
});

test('calling the cancel action cancels a pending_payment booking', function () {
    $booking = Booking::factory()->create(['status' => BookingStatus::PendingPayment]);

    Livewire::test(ListBookings::class)
        ->callTableAction('cancel', $booking)
        ->assertNotified();

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

test('the view action is visible for a user with view_bookings', function () {
    $booking = Booking::factory()->create();

    Livewire::test(ListBookings::class)
        ->assertTableActionVisible('view', $booking);
});

test('the view action is hidden from a non-owner without view_bookings', function () {
    $stranger = User::factory()->create();
    $this->actingAs($stranger);

    $booking = Booking::factory()->create(['user_id' => User::factory()->create()->id]);

    Livewire::test(ListBookings::class)
        ->assertTableActionHidden('view', $booking);
});

test('can view a booking\'s detail page', function () {
    $booking = Booking::factory()->create([
        'passenger_name' => 'Jane Doe',
        'passenger_phone' => '+959123456789',
    ]);

    BookingVehicleOption::factory()->create([
        'booking_id' => $booking->id,
        'vehicle_option' => VehicleOption::BackSeat,
        'passenger_count' => 2,
        'unit_price' => 9000,
        'line_total' => 18000,
    ]);

    Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
        ->assertOk()
        ->assertSee($booking->booking_ref)
        ->assertSee('Jane Doe')
        ->assertSee('+959123456789')
        ->assertSee($booking->route->company->name)
        ->assertSee($booking->pickup_address)
        ->assertSee($booking->dropoff_address);
});

test('the booking detail page shows its related payments', function () {
    $booking = Booking::factory()->create();

    Payment::factory()->completed()->create([
        'booking_id' => $booking->id,
        'gateway' => PaymentMethod::KbzMiniApp,
        'gateway_transaction_id' => 'EVB-INFOLIST-TEST-1',
    ]);

    Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
        ->assertOk()
        ->assertSee('EVB-INFOLIST-TEST-1')
        ->assertSee(PaymentStatus::Completed->value);
});

test('the booking detail page shows a placeholder when there are no payments yet', function () {
    $booking = Booking::factory()->create();

    Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
        ->assertOk()
        ->assertSee('No payment attempts yet.');
});

test('the assign driver action is visible for a confirmed booking and hidden otherwise', function () {
    $confirmed = Booking::factory()->create(['status' => BookingStatus::Confirmed]);
    $pending = Booking::factory()->create(['status' => BookingStatus::PendingPayment]);

    Livewire::test(ListBookings::class)
        ->assertTableActionVisible('assignDriver', $confirmed)
        ->assertTableActionHidden('assignDriver', $pending);
});

test('the assign driver action is hidden once the travel date has passed', function () {
    $past = Booking::factory()->create(['status' => BookingStatus::Confirmed, 'travel_date' => today()->subDay()]);
    $today = Booking::factory()->create(['status' => BookingStatus::Confirmed, 'travel_date' => today()]);

    Livewire::test(ListBookings::class)
        ->assertTableActionHidden('assignDriver', $past)
        ->assertTableActionVisible('assignDriver', $today);
});

test('the assign driver action is hidden from a user without manage_bookings', function () {
    $viewer = User::factory()->create()->givePermissionTo('view_bookings');
    $this->actingAs($viewer);

    $booking = Booking::factory()->create(['status' => BookingStatus::Confirmed]);

    Livewire::test(ListBookings::class)
        ->assertTableActionHidden('assignDriver', $booking);
});

test('calling the assign driver action sets driver and car details on a confirmed booking', function () {
    $booking = Booking::factory()->create(['status' => BookingStatus::Confirmed]);

    Livewire::test(ListBookings::class)
        ->callTableAction('assignDriver', $booking, data: [
            'driver_name' => 'U Aung',
            'driver_phone' => '+959111222333',
            'car_plate_number' => 'YGN-1234',
            'car_model' => 'Tesla Model Y',
        ])
        ->assertNotified();

    $booking->refresh();

    expect($booking->driver_name)->toBe('U Aung')
        ->and($booking->driver_phone)->toBe('+959111222333')
        ->and($booking->car_plate_number)->toBe('YGN-1234')
        ->and($booking->car_model)->toBe('Tesla Model Y');
});

test('the assign driver form requires driver_name, driver_phone, and car_plate_number', function () {
    $booking = Booking::factory()->create(['status' => BookingStatus::Confirmed]);

    Livewire::test(ListBookings::class)
        ->callTableAction('assignDriver', $booking, data: [
            'driver_name' => '',
            'driver_phone' => '',
            'car_plate_number' => '',
        ])
        ->assertHasTableActionErrors(['driver_name' => 'required', 'driver_phone' => 'required', 'car_plate_number' => 'required']);

    expect($booking->refresh()->driver_name)->toBeNull();
});

test('the assign driver form is pre-filled with the booking\'s existing driver/car details', function () {
    $booking = Booking::factory()->create([
        'status' => BookingStatus::Confirmed,
        'driver_name' => 'U Aung',
        'driver_phone' => '+959111222333',
        'car_plate_number' => 'YGN-1234',
        'car_model' => 'Tesla Model Y',
    ]);

    Livewire::test(ListBookings::class)
        ->mountTableAction('assignDriver', $booking)
        ->assertTableActionDataSet([
            'driver_name' => 'U Aung',
            'driver_phone' => '+959111222333',
            'car_plate_number' => 'YGN-1234',
            'car_model' => 'Tesla Model Y',
        ]);
});

test('the detail page also has assign driver and cancel actions, shared with the table', function () {
    $confirmed = Booking::factory()->create(['status' => BookingStatus::Confirmed]);

    Livewire::test(ViewBooking::class, ['record' => $confirmed->getRouteKey()])
        ->assertActionVisible('assignDriver')
        ->assertActionVisible('cancel')
        ->assertActionDisabled('cancel');
});

test('calling assign driver from the detail page sets driver and car details', function () {
    $booking = Booking::factory()->create(['status' => BookingStatus::Confirmed]);

    Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()])
        ->callAction('assignDriver', data: [
            'driver_name' => 'U Aung',
            'driver_phone' => '+959111222333',
            'car_plate_number' => 'YGN-1234',
            'car_model' => 'Tesla Model Y',
        ])
        ->assertNotified();

    expect($booking->refresh()->driver_name)->toBe('U Aung');
});

test('the detail page\'s assign driver action is hidden for a pending_payment booking', function () {
    $pending = Booking::factory()->create(['status' => BookingStatus::PendingPayment]);

    Livewire::test(ViewBooking::class, ['record' => $pending->getRouteKey()])
        ->assertActionHidden('assignDriver')
        ->assertActionEnabled('cancel');
});

test('the delete action is hidden for a pending_payment or confirmed booking, even with manage_bookings', function () {
    $pending = Booking::factory()->create(['status' => BookingStatus::PendingPayment]);
    $confirmed = Booking::factory()->create(['status' => BookingStatus::Confirmed]);

    // authorize('delete') ties visibility straight to BookingPolicy::delete
    // (status + permission combined) — a non-terminal booking never shows
    // this button at all, rather than a dead disabled one.
    Livewire::test(ListBookings::class)
        ->assertTableActionHidden('delete', $pending)
        ->assertTableActionHidden('delete', $confirmed);
});

test('the delete action is visible and enabled for a cancelled or expired booking', function () {
    $cancelled = Booking::factory()->create(['status' => BookingStatus::Cancelled]);
    $expired = Booking::factory()->create(['status' => BookingStatus::Expired]);

    Livewire::test(ListBookings::class)
        ->assertTableActionVisible('delete', $cancelled)
        ->assertTableActionEnabled('delete', $cancelled)
        ->assertTableActionVisible('delete', $expired)
        ->assertTableActionEnabled('delete', $expired);
});

test('the delete action is hidden from a user without manage_bookings', function () {
    $stranger = User::factory()->create();
    $booking = Booking::factory()->create(['status' => BookingStatus::Cancelled]);

    $this->actingAs($stranger);

    Livewire::test(ListBookings::class)
        ->assertTableActionHidden('delete', $booking);
});

test('deleting a cancelled booking soft-deletes it', function () {
    $booking = Booking::factory()->create(['status' => BookingStatus::Cancelled]);

    Livewire::test(ListBookings::class)
        ->callTableAction('delete', $booking)
        ->assertSuccessful();

    expect(Booking::find($booking->id))->toBeNull();
    expect(Booking::withTrashed()->find($booking->id))->not->toBeNull();
    expect(Booking::withTrashed()->find($booking->id)->trashed())->toBeTrue();
});

test('a soft-deleted booking is hidden from the default list but visible via the trashed filter', function () {
    $active = Booking::factory()->create();
    $deleted = Booking::factory()->create();
    $deleted->delete();

    Livewire::test(ListBookings::class)
        ->assertCanSeeTableRecords([$active])
        ->assertCanNotSeeTableRecords([$deleted])
        ->filterTable('trashed', true)
        ->assertCanSeeTableRecords([$active, $deleted]);
});

test('a round trip\'s return leg has no row of its own in the list, only its outbound leg', function () {
    $outbound = Booking::factory()->create(['is_return_leg' => false]);
    $return = Booking::factory()->create([
        'is_return_leg' => true,
        'linked_booking_id' => $outbound->id,
    ]);
    $outbound->update(['linked_booking_id' => $return->id]);

    // Showing both legs as separate rows read as two unrelated bookings
    // rather than one round trip — the return leg is still reachable via
    // the outbound leg's "Linked Leg" link on the detail page.
    Livewire::test(ListBookings::class)
        ->assertCanSeeTableRecords([$outbound])
        ->assertCanNotSeeTableRecords([$return]);
});

test('a round trip\'s price column shows both legs combined', function () {
    $outbound = Booking::factory()->create(['is_return_leg' => false, 'price' => 15000]);
    $return = Booking::factory()->create([
        'is_return_leg' => true,
        'linked_booking_id' => $outbound->id,
        'price' => 20000,
    ]);
    $outbound->update(['linked_booking_id' => $return->id]);

    Livewire::test(ListBookings::class)
        ->assertTableColumnStateSet('price', '35000.00', record: $outbound);
});

test('a one-way booking\'s price column shows just its own price', function () {
    $booking = Booking::factory()->create(['is_return_leg' => false, 'linked_booking_id' => null, 'price' => 15000]);

    Livewire::test(ListBookings::class)
        ->assertTableColumnStateSet('price', '15000.00', record: $booking);
});

test('the restore action is only visible for a trashed booking', function () {
    $active = Booking::factory()->create();
    $deleted = Booking::factory()->create();
    $deleted->delete();

    Livewire::test(ListBookings::class)
        ->filterTable('trashed', true)
        ->assertTableActionHidden('restore', $active)
        ->assertTableActionVisible('restore', $deleted);
});

test('restoring a deleted booking brings it back', function () {
    $booking = Booking::factory()->create();
    $booking->delete();

    Livewire::test(ListBookings::class)
        ->filterTable('trashed', true)
        ->callTableAction('restore', $booking)
        ->assertSuccessful();

    expect(Booking::find($booking->id))->not->toBeNull();
    expect(Booking::find($booking->id)->trashed())->toBeFalse();
});

test('the remark action is visible for a user with manage_bookings', function () {
    $booking = Booking::factory()->create();

    Livewire::test(ListBookings::class)
        ->assertTableActionVisible('setRemark', $booking);
});

test('the remark action is hidden from a user without manage_bookings', function () {
    $viewer = User::factory()->create()->givePermissionTo('view_bookings');
    $this->actingAs($viewer);

    $booking = Booking::factory()->create();

    Livewire::test(ListBookings::class)
        ->assertTableActionHidden('setRemark', $booking);
});

test('calling the remark action sets the staff remark on a booking', function () {
    $booking = Booking::factory()->create();

    Livewire::test(ListBookings::class)
        ->callTableAction('setRemark', $booking, data: [
            'remark' => 'Passenger requested a child seat.',
        ])
        ->assertNotified();

    expect($booking->refresh()->remark)->toBe('Passenger requested a child seat.');
});

test('the remark form is pre-filled with the booking\'s existing remark', function () {
    $booking = Booking::factory()->create(['remark' => 'Existing remark.']);

    Livewire::test(ListBookings::class)
        ->mountTableAction('setRemark', $booking)
        ->assertTableActionDataSet([
            'remark' => 'Existing remark.',
        ]);
});

test('the restore action is hidden from a user without manage_bookings', function () {
    $stranger = User::factory()->create();
    $booking = Booking::factory()->create();
    $booking->delete();

    $this->actingAs($stranger);

    Livewire::test(ListBookings::class)
        ->filterTable('trashed', true)
        ->assertTableActionHidden('restore', $booking);
});

test('the refund action is visible and enabled for a confirmed booking with process_refunds', function () {
    $booking = Booking::factory()->create(['status' => BookingStatus::Confirmed]);

    Livewire::test(ListBookings::class)
        ->assertTableActionVisible('refund', $booking)
        ->assertTableActionEnabled('refund', $booking);
});

test('the refund action is visible but disabled for a pending_payment booking', function () {
    $booking = Booking::factory()->create(['status' => BookingStatus::PendingPayment]);

    Livewire::test(ListBookings::class)
        ->assertTableActionVisible('refund', $booking)
        ->assertTableActionDisabled('refund', $booking);
});

test('the refund action is hidden from a user without process_refunds', function () {
    $viewer = User::factory()->create()->givePermissionTo('view_bookings');
    $this->actingAs($viewer);

    $booking = Booking::factory()->create(['status' => BookingStatus::Confirmed]);

    Livewire::test(ListBookings::class)
        ->assertTableActionHidden('refund', $booking);
});

test('calling the refund action from the bookings list with full refund toggled on refunds the whole balance', function () {
    app(PaymentGatewayFactory::class)->register(PaymentMethod::KbzMiniApp, FakeBookingResourceRefundGateway::class);

    $booking = Booking::factory()->create(['status' => BookingStatus::Confirmed, 'price' => 15000]);
    $payment = Payment::factory()->completed()->create([
        'booking_id' => $booking->id,
        'gateway' => PaymentMethod::KbzMiniApp,
        'amount' => 15000,
        'gateway_transaction_id' => 'EVB-BOOKING-REFUND-1',
    ]);

    Livewire::test(ListBookings::class)
        ->callTableAction('refund', $booking, data: [
            'full_refund' => true,
            'reason' => 'customer requested cancellation',
        ])
        ->assertNotified();

    expect(Refund::where('payment_id', $payment->id)->where('status', RefundStatus::Completed)->where('amount', 15000)->exists())->toBeTrue();
});

test('calling the refund action with full refund toggled off refunds only the given amount', function () {
    app(PaymentGatewayFactory::class)->register(PaymentMethod::KbzMiniApp, FakeBookingResourceRefundGateway::class);

    $booking = Booking::factory()->create(['status' => BookingStatus::Confirmed, 'price' => 15000]);
    $payment = Payment::factory()->completed()->create([
        'booking_id' => $booking->id,
        'gateway' => PaymentMethod::KbzMiniApp,
        'amount' => 15000,
        'gateway_transaction_id' => 'EVB-BOOKING-PARTIAL-1',
    ]);

    Livewire::test(ListBookings::class)
        ->callTableAction('refund', $booking, data: [
            'full_refund' => false,
            'amount' => 5000,
            'reason' => 'customer requested cancellation',
        ])
        ->assertNotified();

    expect(Refund::where('payment_id', $payment->id)->where('status', RefundStatus::Completed)->where('amount', 5000)->exists())->toBeTrue();
});

test('the refund action\'s amount field is capped at the booking\'s payment\'s refundable balance', function () {
    $booking = Booking::factory()->create(['status' => BookingStatus::Confirmed, 'price' => 15000]);
    Payment::factory()->completed()->create([
        'booking_id' => $booking->id,
        'gateway' => PaymentMethod::KbzMiniApp,
        'amount' => 15000,
        'gateway_transaction_id' => 'EVB-BOOKING-MAX-1',
    ]);

    Livewire::test(ListBookings::class)
        ->callTableAction('refund', $booking, data: [
            'full_refund' => false,
            'amount' => 15000.01,
            'reason' => 'reason',
        ])
        ->assertHasTableActionErrors(['amount' => 'max']);

    expect(Refund::where('booking_id', $booking->id)->exists())->toBeFalse();
});

test('the detail page also has a refund action, shared with the table', function () {
    $confirmed = Booking::factory()->create(['status' => BookingStatus::Confirmed]);

    Livewire::test(ViewBooking::class, ['record' => $confirmed->getRouteKey()])
        ->assertActionVisible('refund')
        ->assertActionEnabled('refund');
});
