<?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 CorrectionTest extends TestCase
{
    use RefreshDatabase;

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

        $event = AttendanceEvent::factory()->create([
            'employee_id' => $employee->id, 'site_id' => $site->id, 'direction' => 'IN',
        ]);

        $response = $this->actingAs($admin)->post("/attendance/{$event->id}/correct", [
            'direction' => 'OUT',
            'ts' => now()->format('Y-m-d\TH:i'),
        ]);

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

        $event->refresh();
        $this->assertNotNull($event->corrected_by);

        $replacement = AttendanceEvent::find($event->corrected_by);
        $this->assertEquals('OUT', $replacement->direction);
        $this->assertEquals('manual', $replacement->source);
        $this->assertEquals($event->id, $replacement->corrects_event_id);

        $this->assertDatabaseHas('audit_logs', ['action' => 'attendance.correct']);
    }
}
