<?php

namespace LaraBB\Forum\UI\Web\Requests;

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

/**
 * Class Show
 * @package LaraBB\Forum\UI\Web\Requests
 */
class Show extends FormRequest
{
    /**
     * @var string
     */
    protected $redirectRoute = 'index';
    /**
     * @var Collection|Forum|mixed|null
     */
    public mixed $forum;

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

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

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

        if(!$this->forum->users->isEmpty()) {
            if(!$this->forum->users->contains('uuid', $this->user()->uuid) && $this->user()->groups->max('priority') <= 90) {
                abort(403, __('You are not authorized to view this forum.'));
            }

            return true;
        }

        return true;
    }

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

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