<?php

use App\Models\User;
use Livewire\Livewire;
use Modules\Booking\Models\Booking;
use Modules\Payment\Enums\PaymentMethod;
use Modules\Payment\Enums\PaymentStatus;
use Modules\Payment\Filament\Resources\Payments\Pages\ListPayments;
use Modules\Payment\Filament\Resources\Payments\Pages\ViewPayment;
use Modules\Payment\Models\Payment;
use Spatie\Permission\Models\Permission;

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

test('a user with view_payments can list payments', function () {
    $viewer = User::factory()->create()->givePermissionTo('view_payments');
    $this->actingAs($viewer);

    $payments = Payment::factory()->count(3)->create();

    Livewire::test(ListPayments::class)
        ->assertOk()
        ->assertCanSeeTableRecords($payments);
});

test('can filter payments by status', function () {
    $viewer = User::factory()->create()->givePermissionTo('view_payments');
    $this->actingAs($viewer);

    $pending = Payment::factory()->create(['status' => PaymentStatus::Pending]);
    $completed = Payment::factory()->completed()->create();

    Livewire::test(ListPayments::class)
        ->filterTable('status', PaymentStatus::Completed->value)
        ->assertCanSeeTableRecords([$completed])
        ->assertCanNotSeeTableRecords([$pending]);
});

test('can view a payment\'s detail page', function () {
    $viewer = User::factory()->create()->givePermissionTo('view_payments');
    $this->actingAs($viewer);

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

    Livewire::test(ViewPayment::class, ['record' => $payment->getRouteKey()])
        ->assertOk()
        ->assertSee($booking->booking_ref)
        ->assertSee('EVB-VIEWTEST-1');
});
