<?php

namespace Tests\Feature;

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

class CsvImportTest extends TestCase
{
    use RefreshDatabase;

    public function test_admin_can_import_employees_csv(): void
    {
        $admin = User::factory()->admin()->create();

        $csv = "emp_id,name,active,consent_on\nEMP0100,Test Person,1,2026-01-01\nEMP0101,Another Person,0,\n";
        $file = UploadedFile::fake()->createWithContent('roster.csv', $csv);

        $response = $this->actingAs($admin)->post('/employees-import', ['csv_file' => $file]);
        $response->assertRedirect(route('employees.index'));

        $this->assertDatabaseHas('employees', ['emp_id' => 'EMP0100', 'name' => 'Test Person', 'active' => true]);
        $this->assertDatabaseHas('employees', ['emp_id' => 'EMP0101', 'active' => false]);
    }

    public function test_existing_employee_is_updated_not_duplicated(): void
    {
        $admin = User::factory()->admin()->create();
        Employee::factory()->create(['emp_id' => 'EMP0200', 'name' => 'Old Name']);

        $csv = "emp_id,name,active,consent_on\nEMP0200,New Name,1,2026-02-02\n";
        $file = UploadedFile::fake()->createWithContent('roster.csv', $csv);

        $this->actingAs($admin)->post('/employees-import', ['csv_file' => $file]);

        $this->assertEquals(1, Employee::where('emp_id', 'EMP0200')->count());
        $this->assertDatabaseHas('employees', ['emp_id' => 'EMP0200', 'name' => 'New Name']);
    }
}
