<?php

namespace Tests\Unit;

use App\DTO\UserDTO;
use App\Models\Role;
use App\Models\User;
use App\Services\PersonnelImportService;
use App\Services\PersonnelService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;

class PersonnelServiceTest extends TestCase
{
    use RefreshDatabase;

    protected PersonnelService $personnelService;
    protected PersonnelImportService $importService;

    protected function setUp(): void
    {
        parent::setUp();
        $this->seed();
        $this->personnelService = app(PersonnelService::class);
        $this->importService = app(PersonnelImportService::class);
    }

    public function test_can_create_personnel_with_photo(): void
    {
        Storage::fake('public');

        $admin = User::where('email', 'admin@smkn1gunungagung.sch.id')->first();
        $this->actingAs($admin);

        $guruRole = Role::where('name', 'guru')->first();
        $file = UploadedFile::fake()->image('guru_profile.jpg');

        $dto = UserDTO::fromArray([
            'role_id' => $guruRole->id,
            'shift_id' => null,
            'name' => 'Budi Santoso S.Pd QA',
            'nip_nis' => '199001012015019999',
            'email' => 'budi.santoso.qa@smkn1gunungagung.sch.id',
            'password' => 'password123',
            'is_active' => true,
        ]);

        $personnel = $this->personnelService->createPersonnel($dto, $file);

        $this->assertInstanceOf(User::class, $personnel);
        $this->assertNotNull($personnel->photo_path);
        Storage::disk('public')->assertExists($personnel->photo_path);
    }

    public function test_can_import_personnel_from_csv_file(): void
    {
        $admin = User::where('email', 'admin@smkn1gunungagung.sch.id')->first();
        $this->actingAs($admin);

        $guruRole = Role::where('name', 'guru')->first();

        $csvContent = "Nama,Email,NIP_NIS\n";
        $csvContent .= "Guru Baru A,gurubaruA@smkn1gunungagung.sch.id,199201012020011003\n";
        $csvContent .= "Guru Baru B,gurubaruB@smkn1gunungagung.sch.id,199301012020011004\n";

        $file = UploadedFile::fake()->createWithContent('import_guru.csv', $csvContent);

        $result = $this->importService->importFromFile($file, $guruRole->id);

        $this->assertTrue($result['success']);
        $this->assertEquals(2, $result['imported_count']);
        $this->assertDatabaseHas('users', ['email' => 'gurubaruA@smkn1gunungagung.sch.id']);
        $this->assertDatabaseHas('users', ['email' => 'gurubaruB@smkn1gunungagung.sch.id']);
    }
}
