<?php

namespace App\Http\Requests\Webhook;

use Illuminate\Foundation\Http\FormRequest;

class WebhookUpdateRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        if (auth()->user()->hasRole('administrator')) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        $webhookId = $this->route('id');

        return [
            'name' => 'required|string',
            'url' => 'required|url|unique:webhooks,url,' . $webhookId,
            'events' => 'required',
        ];
    }

    /**
     * Get the custom error messages for validation.
     *
     * @return array<string, string>
     */
    public function messages()
    {
        return [
            'events.required' => 'Please select at least one event.',
        ];
    }

    /**
     * Prepare the data for validation.
     *
     * Here we ensure that the 'events' data is correctly formatted as JSON.
     *
     * @return void
     */
    protected function prepareForValidation(): void
    {
        if ($this->has('events')) {
            $this->merge([
                'events' => json_encode($this->events),
            ]);
        }
    }
}
