<?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;

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

    /**
     * @param FindTask $getForumTask
     * @return bool
     */
    public function authorize(FindTask $getForumTask): bool
    {
        $this->forum = $getForumTask->bySlug($this->route('slug'), ['prefixes']);
        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 postings in this forum.'));
        }

        return true;
    }

    /**
     * @return string[]
     */
    public function rules(): array
    {
        return [
            'slug' => 'required|exists:forums,slug'
        ];
    }

    /**
     * @return array
     */
    public function messages(): array
    {
        return [
            'slug.required' => __('Please specify a forum.'),
            'slug.exists'   => __('The desired forum does not exist.')
        ];
    }

    /**
     * @param null $keys
     * @return array
     */
    public function all($keys = null)
    {
        $data         = parent::all($keys);
        $data['slug'] = $this->route('slug');

        return $data;
    }

    /**
     * @return RedirectResponse
     */
    public function denied(): RedirectResponse
    {
        return redirect()->route('index')->with([
            'error' => __('You are not authorized to create threads in this forum.')
        ]);
    }
}
