<?php

namespace Tests\Feature;

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

class OperatorControllerTest extends TestCase
{
    use RefreshDatabase;

    protected User $user;

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

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

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

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

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

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

        $response->assertRedirect();
        $this->assertDatabaseHas('operators', $operatorData);
    }

    /** @test */
    public function it_can_show_a_operator(): void
    {
        $operator = Operator::factory()->create();

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

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

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

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

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

    /** @test */
    public function it_can_delete_a_operator(): void
    {
        $operator = Operator::factory()->create();

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

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

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

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

    /** @test */
    public function it_can_search_operators(): void
    {
        $operator1 = Operator::factory()->create(['name' => 'Searchable Operator']);
        $operator2 = Operator::factory()->create(['name' => 'Other Operator']);

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

        $response->assertStatus(200)
                ->assertSee($operator1->name)
                ->assertDontSee($operator2->name);
    }
}