<?php

namespace App\Modules\HR\Recruitment\Requests;

use Illuminate\Foundation\Http\FormRequest;

class RecruitmentReportFilterRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()?->can('recruitment.reports.view') ?? false;
    }

    protected function prepareForValidation(): void
    {
        $m = [];
        foreach (['date_from', 'date_to', 'department_id', 'vacancy_id', 'recruiter_id', 'status'] as $key) {
            if ($this->input($key) === '') {
                $m[$key] = null;
            }
        }
        if ($m !== []) {
            $this->merge($m);
        }
    }

    /** @return array<string, mixed> */
    public function rules(): array
    {
        return [
            'date_from' => ['nullable', 'date'],
            'date_to' => ['nullable', 'date', 'after_or_equal:date_from'],
            'department_id' => ['nullable', 'integer', 'exists:departments,id'],
            'vacancy_id' => ['nullable', 'integer', 'exists:recruitment_vacancies,id'],
            'recruiter_id' => ['nullable', 'integer', 'exists:users,id'],
            'status' => ['nullable', 'string', 'max:64'],
        ];
    }

    /** @return array<string, mixed> */
    public function filters(): array
    {
        return array_filter($this->validated(), fn ($v) => $v !== null && $v !== '');
    }
}
