<?php

namespace LaraBB\Thread\Actions;

use LaraBB\Group\Models\Group;
use LaraBB\Group\Tasks\FindTask as FindGroupTask;
use LaraBB\Thread\UI\Web\Requests\Create;
use LaraBB\User\Models\User;
use LaraBB\User\Tasks\FindTask as FindUserTask;

/**
 * Class CreateAction
 * @package LaraBB\Thread\Actions
 */
class CreateAction
{
    /**
     * CreateAction constructor.
     * @param FindGroupTask $findGroupTask
     * @param FindUserTask $findUserTask
     */
    public function __construct(
        private readonly FindGroupTask $findGroupTask,
        private readonly FindUserTask $findUserTask
    ) {

    }

    /**
     * @param Create $request
     * @return array
     */
    public function run(Create $request): array
    {
        $groups = $this->findGroupTask->all()->filter(function (Group $group) use ($request) {
            return $request->user()->groups->max('priority') >= $group->priority;
        });

        $users = $this->findUserTask->all(['groups'])->filter(function (User $user) use ($groups) {
            return !$user->isInGroup(['Guest']);
        });

        return [
            'forum'  => $request->forum,
            'groups' => $groups,
            'users'  => $users
        ];
    }
}
