<?php

namespace Tests\Feature;

use App\Models\Ride;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class RideControllerTest extends TestCase
{
    use RefreshDatabase;

    protected User $user;

    protected function setUp(): void
    {
        parent::setUp();
        $this->user = User::factory()->create();
    }

    /** @test */
    public function it_can_display_rides_index(): void
    {
        Ride::factory()->count(3)->create();

        $response = $this->actingAs($this->user)->get(route('rides.index'));

        $response->assertStatus(200)
                ->assertSee('Rides');
    }

    /** @test */
    public function it_can_create_a_ride(): void
    {
        $rideData = [
            'name' => 'Test Ride',
            'description' => 'Test description',
            'is_active' => true,
        ];

        $response = $this->actingAs($this->user)->post(route('rides.store'), $rideData);

        $response->assertRedirect();
        $this->assertDatabaseHas('rides', $rideData);
    }

    /** @test */
    public function it_can_show_a_ride(): void
    {
        $ride = Ride::factory()->create();

        $response = $this->actingAs($this->user)->get(route('rides.show', $ride));

        $response->assertStatus(200)
                ->assertSee($ride->name);
    }

    /** @test */
    public function it_can_update_a_ride(): void
    {
        $ride = Ride::factory()->create();
        $updateData = [
            'name' => 'Updated Ride',
            'description' => 'Updated description',
            'is_active' => false,
        ];

        $response = $this->actingAs($this->user)->put(route('rides.update', $ride), $updateData);

        $response->assertRedirect();
        $this->assertDatabaseHas('rides', $updateData);
    }

    /** @test */
    public function it_can_delete_a_ride(): void
    {
        $ride = Ride::factory()->create();

        $response = $this->actingAs($this->user)->delete(route('rides.destroy', $ride));

        $response->assertRedirect();
        $this->assertSoftDeleted('rides', ['id' => $ride->id]);
    }

    /** @test */
    public function it_validates_required_fields(): void
    {
        $response = $this->actingAs($this->user)->post(route('rides.store'), []);

        $response->assertSessionHasErrors(['name']);
    }

    /** @test */
    public function it_can_search_rides(): void
    {
        $ride1 = Ride::factory()->create(['name' => 'Searchable Ride']);
        $ride2 = Ride::factory()->create(['name' => 'Other Ride']);

        $response = $this->actingAs($this->user)->get(route('rides.index', ['search' => 'Searchable']));

        $response->assertStatus(200)
                ->assertSee($ride1->name)
                ->assertDontSee($ride2->name);
    }
}