<?php

namespace App\Http\Requests;

use App\Facades\Settings;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Config;
use Illuminate\Validation\Rule;

class StoreSearchFacetRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return Auth::check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, mixed>
     */
    public function rules(): array
    {
        return [
            'position' => [
                'required',
                'integer',
                'between:1,5',
                'unique:search_facets,position',
            ],
            'filter_type' => [
                'required',
                'string',
                Rule::in($this->getEnabledFilterTypes()),
                'unique:search_facets,filter_type',
            ],
            'robots_index' => ['boolean'],
            'robots_follow' => ['boolean'],
        ];
    }

    /**
     * Get filter types that are enabled in settings.
     *
     * @return array<string>
     */
    private function getEnabledFilterTypes(): array
    {
        $facetableFilters = [
            'make',
            'model',
            'body_type',
            'colour',
            'fuel_type',
            'transmission',
            'location',
            'vehicle_type',
            'is_new',
            'franchise',
        ];

        $configFilters = array_keys(Config::get('filter.filters', []));

        return collect($facetableFilters)
            ->filter(fn ($type) => in_array($type, $configFilters))
            ->filter(fn ($type) => Settings::get("automotive-vehicle-filters-{$type}") === true)
            ->values()
            ->toArray();
    }

    /**
     * Get custom error messages.
     *
     * @return array<string, string>
     */
    public function messages(): array
    {
        return [
            'position.between' => 'Position must be between 1 and 5.',
            'position.unique' => 'A facet already exists at this position.',
            'filter_type.in' => 'The selected filter type is not available or not enabled.',
            'filter_type.unique' => 'This filter type is already configured as a facet.',
        ];
    }
}
