<?php

declare(strict_types=1);

namespace apexl\Io\services;

use apexl\Utils\Strings\Camel;

final readonly class EntitySpecificClassNameService
{
    public function class(
        string $baseClass,
        string $entityClass,
        ?string $fallbackClass = null
    ): string {
        $fallbackClass = $fallbackClass ?? $baseClass;

        $class = $this->buildPotentialClass($baseClass, $entityClass);

        return class_exists($class) ? $class : $fallbackClass;
    }

    private function buildPotentialClass(
        string $baseClass,
        string $entityClass,
    ): string {
        $explodedBaseClass = explode('\\', $baseClass);
        $explodedEntityClass = explode('\\', $entityClass);
        $baseClassBasename = $explodedBaseClass[array_key_last($explodedBaseClass)];

        $explodedBaseClass[array_key_last($explodedBaseClass)] = $this->newClassBasename($explodedEntityClass);

        return sprintf("%s%s", implode('\\', $explodedBaseClass), $baseClassBasename);

    }

    protected function newClassBasename(array $explodedEntityClass): string
    {
        return Camel::camelCase(array_pop($explodedEntityClass), true);
    }

    public function hasSpecificClass($baseClass, $entityClass): bool
    {
        $class = $this->buildPotentialClass($baseClass, $entityClass);

        return class_exists($class);
    }
}