<?php

namespace App\Http\Controllers\Api\V1\Carousel\Requests;

use App\Models\CMS\Media\Carousel;
use App\Models\System\Settings\OS;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class CarouselIndexRequest extends FormRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, ValidationRule|array|string>
     */
    public function rules(): array
    {
        return [
            'place' => ['nullable', 'string', Rule::in(array_keys(
                Carousel::places()
            ))],
            'perPage' => ['nullable', 'integer'],
            'fields' => ['nullable', 'string'],
        ];
    }

    /**
     * Handle a passed validation attempt.
     */
    protected function passedValidation(): void
    {
        $fields = [];
        if ($this->fields) {
            $sanitezedFields = validateCommaSeperated($this->fields, Carousel::class);

            $fields['fields'] = ! empty($sanitezedFields) ? $sanitezedFields : ['*'];
        } else {
            $fields['fields'] = ['*'];
        }

        $this->merge([
            'perPage' => $this->perPage ?: 6,
            ...$fields,
        ]);
    }

    /**
     * Get the error messages for the defined validation rules.
     *
     * @return array<string, string>
     */
    public function messages(): array
    {
        return [
            'place.in' => sprintf('Valid sources: %s', implode(', ', array_keys(OS::apps()))),
            'app.in' => sprintf('Valid sources: %s', implode(', ', array_keys(OS::apps()))),
        ];
    }
}
