<?php

namespace App\Modules\HR\Employees\Requests;

use App\Modules\HR\Employees\Models\Employee;
use App\Modules\HR\Employees\Models\EmployeeSkill;
use App\Modules\HR\Employees\Support\EmployeeSkillLevel;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class UpdateEmployeeSkillRequest extends FormRequest
{
    public function authorize(): bool
    {
        /** @var Employee $employee */
        $employee = $this->route('employee');

        return $this->user()?->can('update', $employee) ?? false;
    }

    /** @return array<string, mixed> */
    public function rules(): array
    {
        /** @var Employee $employee */
        $employee = $this->route('employee');
        /** @var EmployeeSkill $skill */
        $skill = $this->route('skill');

        return [
            'name' => [
                'required',
                'string',
                'max:255',
                Rule::unique('employee_skills', 'name')
                    ->where(fn ($q) => $q->where('employee_id', $employee->id))
                    ->ignore($skill->id),
            ],
            'level' => ['required', 'string', Rule::in(EmployeeSkillLevel::all())],
            'years_experience' => ['nullable', 'integer', 'min:0', 'max:60'],
            'is_certified' => ['sometimes', 'boolean'],
            'notes' => ['nullable', 'string', 'max:500'],
        ];
    }

    protected function prepareForValidation(): void
    {
        if ($this->has('is_certified')) {
            $this->merge(['is_certified' => $this->boolean('is_certified')]);
        }
    }
}
