<?php

use App\Models\User;
use Modules\Booking\Models\Booking;
use Spatie\Permission\Models\Permission;

beforeEach(function () {
    Permission::findOrCreate('view_bookings', 'web');

    $this->owner = User::factory()->create();
    $this->token = $this->owner->createToken('test-token')->plainTextToken;
});

test('index lists only the authenticated user\'s own bookings, latest first', function () {
    $mine = Booking::factory()->create(['user_id' => $this->owner->id, 'created_at' => now()->subMinute()]);
    $mineNewer = Booking::factory()->create(['user_id' => $this->owner->id]);
    Booking::factory()->create(['user_id' => User::factory()->create()->id]);

    $this->withHeader('Authorization', "Bearer {$this->token}")
        ->getJson('/api/v1/bookings')
        ->assertSuccessful()
        ->assertJsonCount(2, 'data')
        ->assertJsonPath('data.0.id', $mineNewer->id)
        ->assertJsonPath('data.1.id', $mine->id);
});

test('index rejects unauthenticated requests', function () {
    $this->getJson('/api/v1/bookings')->assertUnauthorized();
});

test('show allows the owner to view their own booking', function () {
    $booking = Booking::factory()->create(['user_id' => $this->owner->id]);

    $this->withHeader('Authorization', "Bearer {$this->token}")
        ->getJson("/api/v1/bookings/{$booking->booking_ref}")
        ->assertSuccessful()
        ->assertJsonPath('data.id', $booking->id);
});

test('show rejects a non-owner without the view_bookings permission', function () {
    $booking = Booking::factory()->create(['user_id' => User::factory()->create()->id]);

    $this->withHeader('Authorization', "Bearer {$this->token}")
        ->getJson("/api/v1/bookings/{$booking->booking_ref}")
        ->assertForbidden();
});

test('show allows an admin/support user (view_bookings permission) to view someone else\'s booking', function () {
    $admin = User::factory()->create();
    $admin->givePermissionTo('view_bookings');
    $adminToken = $admin->createToken('admin-token')->plainTextToken;

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

    $this->withHeader('Authorization', "Bearer {$adminToken}")
        ->getJson("/api/v1/bookings/{$booking->booking_ref}")
        ->assertSuccessful()
        ->assertJsonPath('data.id', $booking->id);
});

test('show rejects unauthenticated requests', function () {
    $booking = Booking::factory()->create();

    $this->getJson("/api/v1/bookings/{$booking->id}")->assertUnauthorized();
});

test('show 404s for a booking that does not exist', function () {
    $this->withHeader('Authorization', "Bearer {$this->token}")
        ->getJson('/api/v1/bookings/EVB-DOES-NOT-EXIST')
        ->assertNotFound();
});
