<?php

namespace App\Modules\HR\Leave\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

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

    /**
     * @return array<string, mixed>
     */
    public function rules(): array
    {
        $tenantId = $this->user()?->tenant_id;

        return [
            'employee_id' => [
                'nullable',
                'integer',
                Rule::exists('employees', 'id')->where(fn ($q) => $q->where('tenant_id', $tenantId)),
            ],
            'year' => ['nullable', 'integer', 'min:2000', 'max:2100'],
        ];
    }

    public function year(): int
    {
        return (int) ($this->validated('year') ?: date('Y'));
    }

    public function employeeId(): ?int
    {
        $id = $this->validated('employee_id');

        return $id !== null ? (int) $id : null;
    }
}
