<?php

declare(strict_types=1);

use App\Models\Department;
use App\Models\Employee;

beforeEach(function (): void {
    seedRoles();
});

it('allows department managers to manage employees in their own department', function (): void {
    $department = Department::factory()->create();
    $otherDepartment = Department::factory()->create();

    $manager = createUserWithRole('department_manager', [
        'department_id' => $department->id,
    ]);

    $ownEmployee = Employee::factory()->create([
        'department_id' => $department->id,
    ]);

    $otherEmployee = Employee::factory()->create([
        'department_id' => $otherDepartment->id,
    ]);

    expect($manager->can('view', $ownEmployee))->toBeTrue()
        ->and($manager->can('update', $ownEmployee))->toBeTrue()
        ->and($manager->can('delete', $ownEmployee))->toBeTrue()
        ->and($manager->can('view', $otherEmployee))->toBeFalse()
        ->and($manager->can('update', $otherEmployee))->toBeFalse()
        ->and($manager->can('delete', $otherEmployee))->toBeFalse();
});

it('allows department managers to create employees', function (): void {
    $department = Department::factory()->create();
    $manager = createUserWithRole('department_manager', [
        'department_id' => $department->id,
    ]);

    expect($manager->can('create', Employee::class))->toBeTrue();
});

it('denies department managers access to employees without a matching department', function (): void {
    $department = Department::factory()->create();
    $manager = createUserWithRole('department_manager', [
        'department_id' => $department->id,
    ]);

    $unassignedEmployee = Employee::factory()->create([
        'department_id' => $otherDepartment = Department::factory()->create()->id,
    ]);

    expect($manager->can('view', $unassignedEmployee))->toBeFalse();
});

it('allows hr managers to access employees across departments', function (): void {
    $hrManager = createUserWithRole('hr_manager');
    $employee = Employee::factory()->create();

    expect($hrManager->can('viewAny', Employee::class))->toBeTrue()
        ->and($hrManager->can('view', $employee))->toBeTrue()
        ->and($hrManager->can('update', $employee))->toBeTrue()
        ->and($hrManager->can('delete', $employee))->toBeTrue();
});
