<?php

namespace LaraBB\Thread\UI\Web\Requests;

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

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

    /**
     * @param FindTask $getThreadTask
     * @return bool
     */
    public function authorize(FindTask $getThreadTask): bool
    {
        $this->thread = $getThreadTask->bySlug($this->route('slug'), [
            'prefix',
            'users',
            'groups',
            'postings' => function($query) {
                return $query->with(['users', 'groups', 'createdBy' => function($query) {
                    return $query->with(['profile', 'groups']);
                }]);
            },
            'forum.category'
        ]);

        if(is_null($this->thread)) {
            abort(404, __('The desired thread does not exist.'));
        }

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

        if (!$this->thread->groups->isEmpty() && $this->thread->groups->min('priority') >= $this->user()->groups->max('priority')) {
            abort(403, __('You are not authorized to view this thread.'));
        }

        if (!$this->thread->users->isEmpty() && is_null($this->thread->users->where('uuid', $this->user()->uuid)->first())) {
            abort(403, __('You are not authorized to view this thread.'));
        }

        return true;
    }

    /**
     * @return string[]
     */
    public function rules(): array
    {
        return [];
    }

    /**
     * @return array
     */
    public function messages(): array
    {
        return [];
    }
}
