<?php

namespace LaraBB\Thread\UI\Web\Requests;

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

/**
 * Class Store
 * @package LaraBB\Thread\UI\Web\Requests
 */
class Store extends FormRequest
{
    /**
     * @var Collection|Forum|mixed|null
     */
    public $forum;

    /**
     * @param FindTask $getForumTask
     * @return bool
     */
    public function authorize(FindTask $getForumTask): bool
    {
        $this->forum = $getForumTask->byUuid($this->post('forum_uuid'));
        if(is_null($this->forum)) {
            abort(404, __('The desired forum does not exist.'));
        }

        if(!$this->user()->forumPermissions[$this->forum->uuid]->create_threads) {
            abort(403, __('You are not authorized to create threads in this forum.'));
        }

        return true;
    }

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

    /**
     * @return array
     */
    public function messages(): array
    {
        return [
            'forum_uuid.uuid'     => __('The given UUID is invalid.'),
            '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('thread-create', [$this->forum->slug])->with([
            'error' => __('Your thread could not be created due to a technical problem.')
        ]);
    }

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