<?php

declare(strict_types=1);

namespace SeoScope\i18n;

use SeoScope\Auth\SessionAuth;
use SeoScope\Database\ConnectionFactory;
use SeoScope\Repositories\SettingsRepository;
use Throwable;

/**
 * Binds the global {@see seoscope_set_translator()} after DB / identity are known.
 */
final class TranslatorBootstrap
{
    public static function registerDefault(string $root): void
    {
        $langDir = $root . '/lang';
        seoscope_set_translator(new Translator(SupportedLocales::DEFAULT, $langDir));
    }

    /**
     * Web UI: session user preference, otherwise English.
     *
     * @param array<string, mixed> $config local.php
     */
    public static function registerForRequest(string $root, array $config): void
    {
        if (!SessionAuth::check()) {
            $langDir = $root . '/lang';
            $fromCookie = SupportedLocales::localeFromCookie();
            $locale = $fromCookie !== null ? $fromCookie : SupportedLocales::DEFAULT;
            seoscope_set_translator(new Translator($locale, $langDir));

            return;
        }
        $user = SessionAuth::user();
        if ($user === null) {
            self::registerDefault($root);

            return;
        }
        self::registerForUserId($root, $config, $user['id']);
    }

    /**
     * Cron / any non-session context where a tenant user id is known.
     *
     * @param array<string, mixed> $config local.php
     */
    public static function registerForUserId(string $root, array $config, int $userId): void
    {
        $langDir = $root . '/lang';
        $locale = SupportedLocales::DEFAULT;
        try {
            $pdo = ConnectionFactory::fromConfig($config);
            $settings = new SettingsRepository($pdo, SEOSCOPE_TABLE_PREFIX, $userId);
            $stored = $settings->get(SupportedLocales::SETTING_KEY);
            $locale = SupportedLocales::normalize($stored);
        } catch (Throwable) {
            $locale = SupportedLocales::DEFAULT;
        }
        seoscope_set_translator(new Translator($locale, $langDir));
    }
}
