<?php

namespace App\Http\Requests\Badges;

use Illuminate\Foundation\Http\FormRequest;

class GenerateBadgePdfRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    protected function prepareForValidation(): void
    {
        $userIds = $this->input('user_ids', []);

        if (is_string($userIds)) {
            $userIds = array_filter(array_map('trim', explode(',', $userIds)), 'strlen');
        } elseif (!is_array($userIds)) {
            $userIds = $userIds ? [$userIds] : [];
        }

        $this->merge([
            'user_ids' => array_values(array_unique(array_map(static fn ($v) => (int) $v, $userIds))),
            'roles' => is_array($this->input('roles')) ? $this->input('roles') : [],
            'classes' => is_array($this->input('classes')) ? $this->input('classes') : [],
        ]);
    }

    public function rules(): array
    {
        return [
            'user_ids' => ['required', 'array', 'min:1'],
            'user_ids.*' => ['integer', 'min:1'],
            'school_year' => ['nullable', 'string', 'max:50'],
            'roles' => ['nullable', 'array'],
            'classes' => ['nullable', 'array'],
        ];
    }
}