<?php

namespace App\Modules\HR\Attendance\Requests;

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

class AttendanceMonthlyReportRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()?->can('attendance.view') === true;
    }

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

        return [
            'month' => ['nullable', 'date_format:Y-m'],
            'employee_id' => [
                'nullable',
                'integer',
                Rule::exists('employees', 'id')->where(fn ($q) => $q->where('tenant_id', $tenantId)),
            ],
        ];
    }

    public function monthOrDefault(): string
    {
        return (string) ($this->validated('month') ?? now()->format('Y-m'));
    }

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

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