<?php

namespace App\Http\Requests;

use App\Rules\ExceedsMaxEnabledCountRule;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Mtc\MercuryDataModels\Setting;

class SettingUpdateRequest extends FormRequest
{
    private array $extraRules = [];
    private Collection $sectionSettings;

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

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return array_merge([
            'settings' => 'array',
            'settings.*.config_key' => 'required',
            'values' => [
                new ExceedsMaxEnabledCountRule($this->input('values'))
            ],
        ], $this->extraRules);
    }

    protected function prepareForValidation()
    {
        $values = collect($this->input('settings'))
            ->pluck('value', 'config_key');

        $this->sectionSettings = Setting::query()
            ->whereIn('config_key', $values->keys())
            ->get();

        $this->extraRules = $this->sectionSettings
            ->filter(fn ($setting) => !empty($setting->validation_rules))
            ->pluck('validation_rules', 'config_key')
            ->keyBy(fn ($rule, $key) => 'values.' . $key)
            ->toArray();

        $this->merge([
            'values' => $values->toArray(),
        ]);
    }

    #[\Override]
    public function attributes()
    {
        return $this->sectionSettings
            ->keyBy(fn ($setting) => 'values.' . $setting->config_key)
            ->map(fn ($setting) => $setting->group . ' > ' . $setting->name)
            ->toArray();
    }
}
