<?php

namespace Tests\Feature;

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

class AttendanceFeatureTest extends TestCase
{
    use RefreshDatabase;

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

    public function test_admin_can_view_employee_list(): void
    {
        $admin = User::where('role', 'super_admin')->first();

        $response = $this->actingAs($admin)->get('/admin/employees');
        $response->assertStatus(200);
        $response->assertSee('Manajemen Karyawan');
    }

    public function test_admin_can_view_attendance_list(): void
    {
        $admin = User::where('role', 'admin')->first();

        $response = $this->actingAs($admin)->get('/admin/attendance');
        $response->assertStatus(200);
        $response->assertSee('Data Kehadiran Karyawan');
    }

    public function test_employee_can_access_checkin_page(): void
    {
        $employeeUser = User::where('email', 'employee@absensi.test')->first();

        $response = $this->actingAs($employeeUser)->get('/employee/attendance/check-in');
        $response->assertStatus(200);
        $response->assertSee('Absensi Masuk');
    }

    public function test_employee_checkin_process_with_valid_coordinates(): void
    {
        $employeeUser = User::where('email', 'joko.widodo@absensi.test')->first();
        $office = OfficeLocation::first();

        $response = $this->actingAs($employeeUser)->postJson('/employee/attendance/check-in', [
            'latitude' => $office->latitude,
            'longitude' => $office->longitude,
            'notes' => 'Hadir tepat di kantor',
        ]);

        $response->assertStatus(200);
        $response->assertJson([
            'success' => true,
        ]);

        $this->assertDatabaseHas('attendances', [
            'employee_id' => $employeeUser->employee->id,
            'status' => 'late',
        ]);
    }

    public function test_employee_cannot_checkin_twice_on_same_day(): void
    {
        $employeeUser = User::where('email', 'joko.widodo@absensi.test')->first();
        $office = OfficeLocation::first();

        // First check-in
        $this->actingAs($employeeUser)->postJson('/employee/attendance/check-in', [
            'latitude' => $office->latitude,
            'longitude' => $office->longitude,
        ]);

        // Second check-in attempt
        $secondResponse = $this->actingAs($employeeUser)->postJson('/employee/attendance/check-in', [
            'latitude' => $office->latitude,
            'longitude' => $office->longitude,
        ]);

        $secondResponse->assertStatus(422);
    }
}
