<?php

namespace App\Http\Requests\Api;

use App\Libs\Security\XSSCleanFilter;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use App\Libs\Support\Sanitizer\Traits\SanitizesInput;
use Illuminate\Validation\ValidationException;

class SearchRequest extends FormRequest
{
    use SanitizesInput;
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules():array
    {
        return [
            'q'             => "required|string",
            'page'          => "nullable|integer|min:1",
            'perPage'       => "nullable|integer|min:1|max:500",
            'contentType'   => "required|string|in:all,document,press",
            'topic'         => "prohibited_unless:contentType,document|nullable|integer",
            'subtopic'      => "prohibited_unless:contentType,document|nullable|integer",
            'documentType'  => "prohibited_unless:contentType,document|nullable|integer",
            'dateStart'     => "prohibited_unless:contentType,document|nullable|date",
            'dateEnd'       => "prohibited_unless:contentType,document|nullable|date",
            'orderBy'       => "nullable|in:alphabetical,date",
            'orderDir'      => "nullable|in:asc,desc",
        ];
    }

    public function filters() {
        return [
            'q'             => "trim|strip_tags|xss_clean",
            'orderBy'       => "trim|strip_tags|xss_clean",
            'orderDir'      => "trim|strip_tags|xss_clean",
        ];
    }

    public function customFilters()
    {
        return ['xss_clean' => XSSCleanFilter::class];
    }

    protected function failedValidation(Validator $validator)
    {
        throw (new ValidationException($validator))
            ->errorBag($this->errorBag);
    }
}
