<?php

namespace Tests\Unit;

use App\DTO\MachineDTO;
use App\Models\FingerprintMachine;
use App\Models\User;
use App\Services\FingerprintMachineService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class FingerprintMachineServiceTest extends TestCase
{
    use RefreshDatabase;

    protected FingerprintMachineService $machineService;

    protected function setUp(): void
    {
        parent::setUp();
        $this->seed();
        $this->machineService = app(FingerprintMachineService::class);
    }

    public function test_can_create_new_machine(): void
    {
        $admin = User::where('email', 'admin@smkn1gunungagung.sch.id')->first();
        $this->actingAs($admin);

        $dto = MachineDTO::fromArray([
            'name' => 'Mesin Fingerprint 7 - Ruang Kepala Sekolah',
            'ip_address' => '192.168.1.207',
            'port' => '4370',
        ]);

        $machine = $this->machineService->createMachine($dto);

        $this->assertInstanceOf(FingerprintMachine::class, $machine);
        $this->assertEquals('192.168.1.207', $machine->ip_address);
        $this->assertDatabaseHas('fingerprint_machines', ['ip_address' => '192.168.1.207']);
    }

    public function test_test_connection_updates_machine_status_and_logs(): void
    {
        $admin = User::where('email', 'admin@smkn1gunungagung.sch.id')->first();
        $this->actingAs($admin);

        $machine = FingerprintMachine::first();

        // Testing connection to invalid IP (127.0.0.1:4370 unopen port) should set status to offline gracefully
        $isOnline = $this->machineService->testConnection($machine);

        $this->assertIsBool($isOnline);
        $this->assertDatabaseHas('sync_logs', ['machine_id' => $machine->id]);
    }
}
