<?php

namespace App\Modules\HR\Attendance\Requests;

use App\Modules\HR\Attendance\Support\AttendanceExceptionSeverity;
use App\Modules\HR\Attendance\Support\AttendanceExceptionStatus;
use App\Modules\HR\Attendance\Support\AttendanceExceptionType;
use Illuminate\Foundation\Http\FormRequest;

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

    protected function prepareForValidation(): void
    {
        $m = [];
        foreach (['type', 'severity', 'status', 'employee_id', 'from', 'to'] as $key) {
            $v = $this->input($key);
            if ($v === '') {
                $m[$key] = null;
            }
        }
        if ($m !== []) {
            $this->merge($m);
        }
    }

    /**
     * @return array<string, array<int, string>>
     */
    public function rules(): array
    {
        $types = implode(',', AttendanceExceptionType::all());
        $sev = implode(',', AttendanceExceptionSeverity::all());
        $status = implode(',', [
            AttendanceExceptionStatus::PENDING,
            AttendanceExceptionStatus::RESOLVED,
            AttendanceExceptionStatus::IGNORED,
        ]);

        return [
            'type' => ['nullable', 'string', 'in:'.$types],
            'severity' => ['nullable', 'string', 'in:'.$sev],
            'status' => ['nullable', 'string', 'in:'.$status],
            'employee_id' => ['nullable', 'integer', 'min:1'],
            'from' => ['nullable', 'date'],
            'to' => ['nullable', 'date', 'after_or_equal:from'],
        ];
    }

    /**
     * @return array{type?: string, severity?: string, status?: string, employee_id?: int, from?: string, to?: string}
     */
    public function filters(): array
    {
        return array_filter($this->validated(), fn ($v) => $v !== null && $v !== '');
    }
}
