<?php

declare(strict_types=1);

namespace apexl\Io\modules\tabulator\Services;

use apexl\Io\includes\Entity;
use apexl\Io\interfaces\RelationshipInterface;

final readonly class TabulatorColumnFieldNameResolver
{
    public function __construct(
        private Entity $entity,
        private TabulatorFieldRenamer $renamer,
    ) {}

    public function resolve(
        string $field,
        ?RelationshipInterface $relation = null,
    ): string {
        $field = $this->field($this->renamer->rename($field));

        if ($relation) {
            if ($this->isRelationDataField($relation, $field)) {
                return sprintf('%s.%s', $relation->getAliasedRemoteTable(), $field);
            }

            if ($this->isRelationVirtualField($relation, $field)) {
                return $relation->getRemoteEntity()->virtualFields()->get($field)->getSql(
                    $relation->getAliasedRemoteTable()
                );
            }
        }


        if ($this->isLocalDataField($field)) {
            return sprintf('%s.%s', $this->entity->getTableName(), $field);
        }

        if ($this->isLocalVirtualField($field)) {
            return $this->entity->virtualFields()->get($field)->getSql();
        }


        return $field;
    }

    private function field($field): string
    {
        $field = explode('__', $field);

        return $field[count($field) - 1];
    }

    public function isRelationDataField(?RelationshipInterface $relation, string $field): bool
    {
        return ($relation && $relation->getRemoteEntity()->isDataField($field));
    }

    public function isRelationVirtualField(?RelationshipInterface $relation, string $field): bool
    {
        return ($relation && $relation->getRemoteEntity()->isVirtualField($field));
    }

    public function isLocalDataField(string $field): bool
    {
        return ($this->entity->isDataField($field));
    }

    public function isLocalVirtualField(string $field): bool
    {
        return $this->entity->isVirtualField($field);
    }

}