<?php

declare(strict_types=1);

namespace Core\General\Translation\Service;

use Core\General\Translation\Exception\TranslationException;
use Core\General\Translation\ValueObject\TranslationTuple;
use Symfony\Contracts\Translation\TranslatorInterface;

readonly class Translator
{
    public function __construct(
        private TranslatorInterface $translator,
    ) {
    }

    /**
     * Translate message given as string, TranslationTuple or array value. If array is provided, apply recursion.
     *
     * @param mixed[] $parameters
     *
     * @return ($message is string ? string : array<string, mixed>)
     *
     * @throws TranslationException
     */
    public function translateMessage(mixed $message, array $parameters = [], ?string $domain = null, ?string $locale = null): string|array
    {
        if (\is_string($message)) {
            return $this->translator->trans($message, $parameters, $domain, $locale);
        }
        if ($message instanceof TranslationTuple) {
            return $this->translator->trans($message->getMessage(), $message->getParams(), $domain, $locale);
        }
        if (!\is_array($message)) {
            throw TranslationException::becauseUnexpectedTypeProvided();
        }

        $translatedErrors = [];
        foreach ($message as $key => $value) {
            $translatedErrors[$key] = $this->translateMessage($value);
        }

        return $translatedErrors;
    }
}
