<?php

declare(strict_types=1);

namespace Signocore\Multilanguage\Features;

if (!defined('ABSPATH')) {
	exit;
}

use Signocore\Multilanguage\Infrastructure\Database\StringRepository;
use Signocore\Multilanguage\Infrastructure\Traits\Singleton;

final class StringTranslation
{
	use Singleton;

	/** @var array<string, string> */
	private static array $cache = [];

	protected function init(): void
	{
		add_action('signocore_ml_register_string', [$this, 'registerString'], 10, 4);
	}

	/**
	 * Register a translatable string.
	 */
	public function registerString(string $context, string $name, string $value, string $type = 'line'): void
	{
		$defaultLangCode = LanguageManager::load()->getDefaultLanguageCode();

		$existing = StringRepository::findString($context, $name);
		$valueChanged = $existing !== null && $existing->value !== $value;

		$stringId = StringRepository::registerString($context, $name, $value, $defaultLangCode, $type);

		if ($valueChanged && $stringId > 0) {
			StringRepository::markNeedsUpdate($stringId);
		}
	}

	/**
	 * Translate a registered string to the current language.
	 */
	public function translateString(string $context, string $name, string $default = ''): string
	{
		$currentLang = LanguageDetection::load()->getCurrentLanguage();
		$defaultLang = LanguageManager::load()->getDefaultLanguageCode();

		if ($currentLang === $defaultLang) {
			return $default;
		}

		$cacheKey = "{$context}::{$name}::{$currentLang}";

		if (isset(self::$cache[$cacheKey])) {
			return self::$cache[$cacheKey];
		}

		$string = StringRepository::findString($context, $name);

		if ($string === null) {
			self::$cache[$cacheKey] = $default;
			return $default;
		}

		$translation = StringRepository::getTranslationValue((int) $string->id, $currentLang);

		$result = $translation !== null ? $translation : $default;
		self::$cache[$cacheKey] = $result;

		return $result;
	}

	/**
	 * Clear the static translation cache.
	 */
	public function clearCache(): void
	{
		self::$cache = [];
	}
}
