<?php

namespace LaraBB\Forum\Actions\Admin;

use JetBrains\PhpStorm\ArrayShape;
use LaraBB\Category\Tasks\FindTask as FindCategoryTask;
use LaraBB\Group\Models\Group;
use LaraBB\Group\Tasks\FindTask as FindGroupTask;
use LaraBB\User\Models\User;

/**
 * Class CreateAction
 * @package LaraBB\Forum\Actions\Admin
 */
class CreateAction
{
    /**
     * CreateAction constructor.
     * @param FindGroupTask $findGroupTask
     * @param FindCategoryTask $findCategoryTask
     */
    public function __construct(
        private readonly FindGroupTask $findGroupTask,
        private readonly FindCategoryTask $findCategoryTask
    ) {
    }

    /**
     * @return array
     */
    #[ArrayShape([
        'categories' => "array|\Illuminate\Database\Eloquent\Collection",
        'users'      => "mixed",
        'groups'     => "array|\Illuminate\Database\Eloquent\Collection",
        'active'     => "string"
    ])]
    public function run(): array
    {
        $users  = collect();
        $groups = $this->findGroupTask->all(['users']);

        $groups->map(function ($group) use ($users) {
            /** @var Group $group */
            $group->users->map(function ($user) use ($users) {

                /** @var User $user */
                if (!$users->contains('uuid', $user->uuid)) {
                    $users->push($user);
                }
            });

            $group->unsetRelation('users');
        });

        return [
            'categories' => $this->findCategoryTask->all(),
            'users'      => $users,
            'groups'     => $groups,
            'active'     => 'forums',
        ];
    }
}
