<?php

namespace Tests\Feature;

use App\Models\AttendanceEvent;
use App\Models\Employee;
use App\Models\Site;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class ManualEntryTest extends TestCase
{
    use RefreshDatabase;

    public function test_manual_entry_creates_event_with_expected_attributes_and_audit_log(): void
    {
        $site = Site::factory()->create();
        $employee = Employee::factory()->create();
        $hr = User::factory()->hr()->create();

        $response = $this->actingAs($hr)->post('/manual-entry', [
            'emp_id' => $employee->emp_id,
            'site_id' => $site->id,
            'direction' => 'IN',
            'ts' => now()->format('Y-m-d\TH:i'),
        ]);

        $response->assertRedirect(route('attendance.manual-entry'));

        $event = AttendanceEvent::first();
        $this->assertEquals('manual', $event->source);
        $this->assertEquals(1.0, $event->confidence);
        $this->assertEquals($hr->name, $event->operator);

        $this->assertDatabaseHas('audit_logs', ['action' => 'attendance.manual_entry', 'user_id' => $hr->id]);
    }

    public function test_security_cannot_manual_entry_for_other_site(): void
    {
        $ownSite = Site::factory()->create();
        $otherSite = Site::factory()->create();
        $employee = Employee::factory()->create();
        $security = User::factory()->security()->create(['site_id' => $ownSite->id]);

        $response = $this->actingAs($security)->post('/manual-entry', [
            'emp_id' => $employee->emp_id,
            'site_id' => $otherSite->id,
            'direction' => 'IN',
            'ts' => now()->format('Y-m-d\TH:i'),
        ]);

        $response->assertForbidden();
    }
}
