<?php

declare(strict_types=1);

namespace apexl\Io\services;

use apexl\Io\includes\Entity;
use apexl\Io\interfaces\RelationshipInterface;
use apexl\Io\modules\tabulator\Services\TabulatorFieldRenamer;

final readonly class RelationResolver
{
    public function __construct(private TabulatorFieldRenamer $renamer) {}

    /** @param class-string<Entity>|Entity $entity */
    public function resolve(
        string $relation,
        string|Entity $entity,
        ?RelationshipInterface $parent = null
    ): ?RelationshipInterface {
        if (is_string($entity)) {
            $entity = new $entity();
        }
        $relation = $this->renamer->rename($relation);
        $parts = explode('__', $relation);

        $_relation = array_shift($parts);

        /** @var ?RelationshipInterface $relationObject */
        $relationObject = $entity->relations()->get($_relation);

        if ($relationObject === null) {
            return null;
        }

        if ($parent) {
            $relationObject = $relationObject->with([
                'parent' => $parent,
                'localTable' => $parent->getAliasedRemoteTable(),
            ]);
        }

        if (count($parts) > 1) {
            return $this->resolve(
                implode('__', $parts),
                $relationObject->remoteEntity,
                $relationObject
            );
        }

        return $relationObject->with('localEntity', $entity);
    }
}
