<?php

namespace LaraBB\Thread\Actions;

use LaraBB\Post\Models\Post;
use LaraBB\Thread\Tasks\UpdateTask as UpdateThreadTask;
use LaraBB\Thread\UI\Web\Requests\Show;

/**
 * Class ShowAction
 * @package LaraBB\Thread\Actions
 */
class ShowAction
{
    /**
     * ShowAction constructor.
     * @param UpdateThreadTask $updateThreadTask
     */
    public function __construct(private readonly UpdateThreadTask $updateThreadTask)
    {

    }

    /**
     * @param Show $request
     * @return array
     */
    public function run(Show $request): array
    {
        $thread = $request->thread;
        $this->updateThreadTask->run($thread, [
            'views' => $thread->views + 1
        ]);

        $thread->postings = $thread->postings->filter(function(Post $post) use($request) {
            if($post->groups->isEmpty()) {
                return true;
            }

            return $post->groups->min('priority') <= $request->user()->groups->max('priority');
        });

        $thread->postings = $thread->postings->filter(function(Post $post) use($request) {
            if($post->users->isEmpty()) {
                return true;
            }

            return $post->users->contains('uuid', $request->user()->uuid) || $post->created_uuid == $request->user()->uuid;
        });

        return [
            'thread'   => $thread,
            'posts'    => $thread->postings,
            'forum'    => $thread->forum,
            'category' => $thread->forum->category
        ];
    }
}
