<?php

namespace LaraBB\Post\UI\Web\Requests;

use Illuminate\Database\Eloquent\Collection;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\RedirectResponse;
use LaraBB\Thread\Models\Thread;
use LaraBB\Thread\Tasks\FindTask;

class Store extends FormRequest
{
    /**
     * @var Collection|Thread|mixed|null
     */
    public ?Thread $thread;

    /**
     * @param FindTask $getThreadTask
     * @return bool
     */
    public function authorize(FindTask $getThreadTask): bool
    {
        $this->thread = $getThreadTask->byUuid($this->post('thread_uuid'), ['forum']);

        if(!$this->user()->forumPermissions[$this->thread->forum_uuid]->create_posts) {
            abort(403, __('You are not authorized to create posts in this thread.'));
        }

        return true;
    }

    /**
     * @return string[]
     */
    public function rules(): array
    {
        return [
            'thread_uuid' => 'required|uuid|exists:threads,uuid',
            'title'       => 'required|min:5',
            'content'     => 'required|min:20'
        ];
    }

    /**
     * @return array
     */
    public function messages(): array
    {
        return [
            'thread_uuid.required' => __('No UUID was passed.'),
            'thread_uuid.uuid'     => __('The given UUID is invalid.'),
            'thread_uuid.exists'   => __('The desired thread does not exist.'),
            'title.required'       => __('Please enter a title!'),
            'title.min'            => __('The title must be at least :min characters long.'),
            'content.required'     => __('Please enter a content!'),
            'content.min'          => __('The content must be at least :min characters long.')
        ];
    }

    /**
     * @return RedirectResponse
     */
    public function failed(): RedirectResponse
    {
        return redirect()->route('reply', [$this->thread->slug])->with([
            'error' => __('Your posting could not be created due to a technical problem.')
        ]);
    }

    /**
     * @param int $postId
     * @return RedirectResponse
     */
    public function success(int $postId): RedirectResponse
    {
        return redirect()->route('thread', [$this->thread->slug, '#post-' . $postId])->with([
            'success' => __('Your post was successfully created.')
        ]);
    }
}
