<?php

namespace apexl\Io\modules\BasicApi\Services;

use app\module\newtonsTrailers\Entity\Entity;

class BasicModuleEntityStore
{
    /** @var array<string, Entity[]> */
    protected array $entities;

    public function add(string $module, Entity|array $entities): void
    {
        if (is_array($entities)) {
            foreach ($entities as $entity) {
                $this->add($module, $entity);
            }

            return;
        }

        if (!isset($this->entities[$module][$entities::class])) {
            $this->entities[$module][$entities::class] = $entities;
        }
    }

    /**
     * @return Entity[]
     */
    public function all(string $module, ?string $type = null): array
    {
        $entities = $this->entities[$module] ?? [];

        if ($type) {
            $entities = array_filter(
                $entities,
                fn(Entity $entity): bool => is_a($entity, $type)
            );
        }

        return $entities;
    }

}
