<?php

declare(strict_types=1);

namespace App\Http\Requests\Discussion;

use Illuminate\Foundation\Http\FormRequest;

class UpdateDiscussionRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        return [
            'title' => ['sometimes', 'required', 'string', 'min:2', 'max:255'],
            'hashtag' => ['nullable', 'string', 'max:100'],
        ];
    }

    public function messages(): array
    {
        return [
            'title.required' => 'نام بحث الزامی است.',
        ];
    }

    protected function prepareForValidation(): void
    {
        if ($this->has('hashtag') && $this->filled('hashtag')) {
            $hashtag = ltrim((string) $this->input('hashtag'), '#');
            $this->merge(['hashtag' => $hashtag !== '' ? '#' . $hashtag : null]);
        }
    }
}
