<?php

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

use App\Models\Ecommerce\Channel\Channel;
use Illuminate\Foundation\Http\FormRequest;

class ChannelIndexRequest 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 [
            'perPage' => ['nullable', 'integer'],
            'fields' => ['nullable', 'string'],
        ];
    }

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

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

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