<?php

declare(strict_types=1);

namespace apexl\Io\collections;

use apexl\Io\dto\VirtualFieldDefinition;
use apexl\Io\includes\Entity;
use Arrayy\Collection\AbstractCollection;

/**
 * @extends AbstractCollection<array-key, VirtualFieldDefinition>
 * @method VirtualFieldDefinition get($key = null, $fallback = null, array $array = null, bool $useByReference = false)
 */
final class VirtualFieldDefinitionCollection extends AbstractCollection
{
    public static function createFromArray(array $array, ?Entity $entity = null): VirtualFieldDefinitionCollection
    {
        $array = array_map(function (string|VirtualFieldDefinition $field) use ($entity): VirtualFieldDefinition {
            if ($field instanceof VirtualFieldDefinition) {
                return $field;
            }

            return $entity?->virtualFields()->get($field);

        }, $array);

        return parent::createFromArray($array);
    }

    public function getType(): string
    {
        return VirtualFieldDefinition::class;
    }

    public function toAliasedSelects(): array
    {
        return $this->map(fn(VirtualFieldDefinition $definition): string => $definition->toAliasedSelect())
            ->toArray();
    }
}
