<?php

declare(strict_types=1);

namespace apexl\Io\collections;

use apexl\Io\includes\Entity;
use apexl\Io\interfaces\RelationshipInterface;
use apexl\Vault\interfaces\driver;
use Arrayy\Collection\AbstractCollection;

/**
 * @extends AbstractCollection<RelationshipInterface>
 */
final class RelationCollection extends AbstractCollection
{
    public static function normaliseWith(array $with, Entity $entity): RelationCollection
    {
        $collection = new RelationCollection();

        foreach ($with as $value) {
            $relation = $value;

            if (is_string($relation)) {
                $relation = $entity->relation($relation);
            }

            $collection->push($relation);
        }

        return $collection;
    }

    public function applyToQuery(driver $query, AppliedRelationCollection $applied): driver
    {
        foreach ($this->toArray() as $relation) {
            $query = $relation->applyToQuery($query, $applied);
        }

        return $query;
    }

    public function byName(string $name): ?RelationshipInterface
    {
        return array_find($this->toArray(), fn($relation) => $relation->name === $name);
    }

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

    public function names(): array
    {
        return $this->map(fn(RelationshipInterface $relation) => $relation->name)->toArray();
    }
}
