<?php

namespace LaraBB\Forum\Actions\Admin;

use JetBrains\PhpStorm\ArrayShape;
use LaraBB\Forum\Tasks\Forum\FindTask as FindForumTask;
use LaraBB\Category\Tasks\FindTask as FindCategoryTask;
use LaraBB\Forum\UI\Web\Requests\Edit;
use LaraBB\Group\Models\Group;
use LaraBB\Group\Tasks\FindTask as FindGroupTask;
use LaraBB\User\Models\User;

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

    }

    /**
     * @param Edit $request
     * @return array
     */
    #[ArrayShape([
        'forum'      => "\LaraBB\Forum\Models\Forum",
        'categories' => "array|\Illuminate\Database\Eloquent\Collection",
        'users'      => "mixed",
        'groups'     => "array|\Illuminate\Database\Eloquent\Collection",
        'active'     => "string"
    ])]
    public function run(Edit $request): 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 [
            'forum'      => $this->findForumTask->byUuid($request->route('uuid'), ['users', 'permissions']),
            'categories' => $this->findCategoryTask->all(),
            'users'      => $users,
            'groups'     => $groups,
            'active'     => 'forums',
        ];
    }
}
