<?php

namespace Tests\Feature;

use App\Models\AttendanceLog;
use App\Models\FingerprintMachine;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class AdmsTest extends TestCase
{
    use RefreshDatabase;

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

    public function test_adms_getrequest_heartbeat_returns_ok(): void
    {
        $machine = FingerprintMachine::create([
            'name' => 'Mesin ADMS Lobby',
            'ip_address' => '192.168.1.201',
            'cloud_id' => 'REVO-W230N-001',
            'connection_type' => 'adms',
            'protocol' => 'adms_push',
        ]);

        $response = $this->get('/iclock/getrequest?SN=REVO-W230N-001');

        $response->assertStatus(200);
        $this->assertEquals('OK', $response->getContent());

        $machine->refresh();
        $this::assertEquals('online', $machine->status);
    }

    public function test_adms_cdata_post_ingests_attendance_logs(): void
    {
        $machine = FingerprintMachine::create([
            'name' => 'Mesin ADMS Lobby',
            'ip_address' => '192.168.1.201',
            'cloud_id' => 'REVO-W230N-002',
            'connection_type' => 'adms',
            'protocol' => 'adms_push',
        ]);

        $payload = "1001\t2026-08-10 07:15:00\t0\t1\r\n1002\t2026-08-10 07:16:30\t0\t1";

        $response = $this->call('POST', '/iclock/cdata?SN=REVO-W230N-002&table=ATTLOG', [], [], [], [], $payload);

        $response->assertStatus(200);
        $this->assertStringContainsString('OK', $response->getContent());

        $this->assertDatabaseHas('attendance_logs', [
            'raw_user_id' => '1001',
            'timestamp' => '2026-08-10 07:15:00',
        ]);
        $this->assertDatabaseHas('attendance_logs', [
            'raw_user_id' => '1002',
            'timestamp' => '2026-08-10 07:16:30',
        ]);
    }
}
