<?php

namespace LaraBB\Category\Actions;

use JetBrains\PhpStorm\ArrayShape;
use LaraBB\Category\Models\Category;
use LaraBB\Category\Tasks\FindTask as FindCategoryTask;
use LaraBB\Category\Traits\ForumsTrait;
use LaraBB\Category\UI\Web\Requests\Index;
use LaraBB\Forum\Models\Forum;

/**
 * Class IndexAction
 * @package LaraBB\Category\Actions
 */
class IndexAction
{
    use ForumsTrait;

    /**
     * IndexAction constructor.
     * @param FindCategoryTask $findCategoryTask
     */
    public function __construct(private readonly FindCategoryTask $findCategoryTask)
    {
    }

    /**
     * @param Index $request
     * @return array
     */
    #[ArrayShape([
        'categories' => "array|\Illuminate\Database\Eloquent\Collection"
    ])]
    public function run(Index $request): array
    {
        $categories = $this->findCategoryTask->all([
            'forums' => function ($query) {
                $query->with([
                    'users',
                    'lastpost' => function ($query) {
                        return $query->with(['thread', 'createdBy']);
                    }
                ]);
            }
        ])->filter(function (Category $category) use ($request) {
            $category->forums = $this->getForums($category, $request);

            return $category->forums->count() > 0;
        });

        return [
            'categories' => $categories
        ];
    }
}
