<?php

namespace Tests\Feature\Api;

use App\Models\Device;
use App\Models\Employee;
use App\Models\Site;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Str;
use Tests\TestCase;

class RosterTest extends TestCase
{
    use RefreshDatabase;

    protected function makeDevice(): array
    {
        $site = Site::factory()->create();
        $token = Str::random(64);
        $device = Device::factory()->create(['site_id' => $site->id, 'token_hash' => hash('sha256', $token)]);

        return [$device, $token];
    }

    public function test_full_snapshot_returns_all_current_employees(): void
    {
        [, $token] = $this->makeDevice();
        Employee::factory()->count(3)->create();

        $response = $this->withHeaders(['X-Device-Token' => $token])->getJson('/api/v1/roster');
        $response->assertOk();
        $response->assertJsonCount(3, 'employees');
        $this->assertEquals([], $response->json('deleted'));
    }

    public function test_delta_sync_returns_only_updated_and_deleted(): void
    {
        [, $token] = $this->makeDevice();

        $old = Employee::factory()->create(['updated_at' => now()->subDays(5)]);
        $cutoff = now()->subDay()->toIso8601String();
        $new = Employee::factory()->create();
        $deleted = Employee::factory()->create();
        $deleted->delete();

        $response = $this->withHeaders(['X-Device-Token' => $token])->getJson('/api/v1/roster?since='.urlencode($cutoff));
        $response->assertOk();

        $empIds = collect($response->json('employees'))->pluck('emp_id')->all();
        $this->assertContains($new->emp_id, $empIds);
        $this->assertNotContains($old->emp_id, $empIds);
        $this->assertContains($deleted->emp_id, $response->json('deleted'));
    }

    public function test_inactive_employee_still_appears_with_active_false(): void
    {
        [, $token] = $this->makeDevice();
        $employee = Employee::factory()->inactive()->create();

        $response = $this->withHeaders(['X-Device-Token' => $token])->getJson('/api/v1/roster');
        $response->assertOk();

        $match = collect($response->json('employees'))->firstWhere('emp_id', $employee->emp_id);
        $this->assertNotNull($match);
        $this->assertFalse($match['active']);
    }
}
