<?php

declare(strict_types=1);

namespace apexl\Io\modules\tabulator\Services;

use apexl\Io\collections\VirtualFieldDefinitionCollection;
use apexl\Io\dto\VirtualFieldDefinition;
use apexl\Io\modules\tabulator\Interfaces\HasTabulatorViewInterface;
use Arrayy\Type\StringCollection;

final readonly class TabulatorEntityFieldResolver
{
    public function __construct(
        private HasTabulatorViewInterface $entity
    ) {}

    public function dataFields(StringCollection $fields): StringCollection
    {
        if ($fields->isEmpty()) {
            return StringCollection::createFromArray([
                sprintf('%s.*', $this->entity->getTableName()),
            ]);
        }

        return $fields
            ->filter(fn(string $field): bool => $this->entity->isDataField($field))
            ->map(fn(string $field): string => sprintf('%s.%s', $this->entity->getTableName(), $field));
    }

    public function with(StringCollection $fields): StringCollection|false
    {
        if ($fields->isEmpty()) {
            return false;
        }

        return $fields
            ->filter(
                fn(string $field): bool => $this->entity->isRelationField($field)
            );
    }

    public function virtual(StringCollection $fields): VirtualFieldDefinitionCollection
    {
        if ($fields->isEmpty()) {
            return new VirtualFieldDefinitionCollection();
        }

        $virtualFields = $this->entity->virtualFields();
        $requestedVirtualFields = $fields
            ->filter(fn(string $field): bool => $this->entity->isVirtualField($field))
            ->values();

        $virtualFields = $virtualFields->toArray();

        $virtualFields = array_filter(
            $virtualFields,
            static fn(VirtualFieldDefinition $field): bool => in_array(
                $field->field,
                $requestedVirtualFields->toArray()
            ),
        );


        return VirtualFieldDefinitionCollection::createFromArray($virtualFields);
    }
}