<?php

namespace Tests\Feature;

use App\Livewire\Machines\MachineIndex;
use App\Models\FingerprintMachine;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
use Tests\TestCase;

class MachineTest extends TestCase
{
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();
        $this->seed();
    }

    public function test_authenticated_admin_can_access_machines_page(): void
    {
        $admin = User::where('email', 'admin@smkn1gunungagung.sch.id')->first();
        $admin->update(['force_password_change' => false]);
        $this->actingAs($admin);

        $response = $this->get('/machines');
        $response->assertStatus(200);
    }

    public function test_can_add_machine_via_livewire(): void
    {
        $admin = User::where('email', 'admin@smkn1gunungagung.sch.id')->first();
        $admin->update(['force_password_change' => false]);
        $this->actingAs($admin);

        Livewire::test(MachineIndex::class)
            ->set('name', 'Mesin Test Lab')
            ->set('ip_address', '192.168.1.250')
            ->set('port', '4370')
            ->set('personnel_target', 'siswa')
            ->call('save')
            ->assertHasNoErrors();

        $this->assertDatabaseHas('fingerprint_machines', [
            'ip_address' => '192.168.1.250',
            'personnel_target' => 'siswa',
        ]);
    }

    public function test_can_update_machine_personnel_target(): void
    {
        $admin = User::where('email', 'admin@smkn1gunungagung.sch.id')->first();
        $admin->update(['force_password_change' => false]);
        $this->actingAs($admin);

        $machine = FingerprintMachine::first();

        Livewire::test(MachineIndex::class)
            ->call('edit', $machine->id)
            ->set('personnel_target', 'guru')
            ->call('save')
            ->assertHasNoErrors();

        $this->assertDatabaseHas('fingerprint_machines', [
            'id' => $machine->id,
            'personnel_target' => 'guru',
        ]);
    }
}
