<?php

use App\Enums\UserStatus;
use App\Livewire\Studio\Master\User\Index;
use App\Models\Employee;
use App\Models\ReferralCode;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

beforeEach(function () {
    $this->user = User::factory()->create();
});

it('renders user index page successfully', function () {
    Livewire::actingAs($this->user)
        ->test(Index::class)
        ->assertViewIs('livewire.studio.master.user.index')
        ->assertViewHas('pageTitle', 'Pegawai');
});

it('mounts employees correctly', function () {
    $userWithEmployee = User::factory()
        ->has(Employee::factory())
        ->has(ReferralCode::factory())
        ->create();

    $employee = $userWithEmployee->employee;

    Livewire::actingAs($this->user)
        ->test(Index::class)
        ->assertSee($employee->full_name)
        ->assertSet('employees.0.full_name', $employee->full_name)
        ->assertSet('employees.0.user.id', $userWithEmployee->id)
        ->assertSet('employees.0.referral_code', $userWithEmployee?->referralCode?->code);
});

it('filters employees by status', function () {
    $activeUser = User::factory()->create(['status' => UserStatus::ACTIVE->value]);
    $inactiveUser = User::factory()->create(['status' => UserStatus::INACTIVE->value]);

    $activeUser->employee()->save(Employee::factory()->make());
    $inactiveUser->employee()->save(Employee::factory()->make());

    $component = Livewire::actingAs($this->user)
        ->test(Index::class);

    $component->set('status', [UserStatus::ACTIVE->value]);

    $employees = $component->employees;
    expect(count($employees))->toBe(1);
    expect($employees[0]['user']['id'])->toBe($activeUser->id);
});

it('deletes a user successfully', function () {
    $userToDelete = User::factory()
        ->has(Employee::factory())
        ->create();

    Livewire::actingAs($this->user)
        ->test(Index::class)
        ->call('delete', $userToDelete)
        ->assertHasNoErrors();

    $this->assertSoftDeleted('users', ['id' => $userToDelete->id]);
});
