<?php

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

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

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

    /**
     * Handle a passed validation attempt.
     */
    protected function passedValidation(): void
    {
        $fields = [];
        if ($this->fields) {
            $sanitezedFields = validateCommaSeperated($this->fields, Banner::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()))),
        ];
    }
}
