<?php

namespace App\Http\Requests;

use App\Models\NotificationMap;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Illuminate\Validation\Validator;

class StoreNotificationMap 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, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:255'],
            'type' => ['nullable', 'string', 'max:60'],
            'template_id' => ['nullable', 'integer'],
        ];
    }

    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator) {
            // The slug is derived from the name; reject names that resolve to a slug
            // already served by a fixed inbound notification route.
            $slug = Str::slug((string) $this->input('name'));

            if (in_array($slug, NotificationMap::RESERVED_SLUGS, true)) {
                $validator->errors()->add('name', 'This name is reserved and cannot be used for a notification.');
            }
        });
    }
}
