<?php

declare(strict_types=1);

namespace Plugin\tnt_mcp\src\Mcp\Admin;

use JTL\Shop;
use Throwable;

/**
 * Picks DE or EN for a piece of *backend* text.
 *
 * Why this exists rather than the shop's usual mechanisms:
 *  - `info.xml` `<Locales>` (the pattern sibling plugins tnt_antispam / tnt_coupons use) localizes
 *    **frontend** variables per SHOP language and is edited by the merchant. The strings here are
 *    security warnings for the backend operator; they must not be merchant-editable and they follow
 *    the ADMIN language, which is a different axis entirely.
 *  - `\__()` resolves against the shop's gettext domains, which a plugin cannot add keys to.
 *
 * So the two texts travel together in a `['de' => …, 'en' => …]` array and this class only decides
 * which one to show. It started as the Q2 rights texts alone — a missing-permission report has to be
 * actionable for a non-German-speaking operator too — and now carries the whole admin UI:
 *
 *  - PHP: build the pair, hand it to {@see self::pick()} (or, in a tab controller, to
 *    `BaseAdminController::text()`, which binds the language for the request). Longer multi-sentence
 *    texts split into a `…De()` / `…En()` method pair instead, see {@see PermissionAudit}.
 *  - Smarty: `{if $lang == 'en'}…{else}…{/if}`. `$lang` is assigned to every tab template by
 *    `BaseAdminController::fetch()`, so a template never has to resolve the language itself.
 *
 * The only strings that stay German are the Customlink tab names in info.xml: JTL stores them in the
 * DB and adminmenu/index.php dispatches on the stored name, so they are identifiers, not prose.
 *
 * `tests/Unit/AdminUiLocalisationTest.php` fails the build on German prose that skips either shape.
 *
 * Falls back to German — the plugin's existing UI language — whenever the admin session is not
 * readable (CLI, install hook before a session exists, …).
 */
final class AdminLanguage
{
    public const DE = 'de';

    public const EN = 'en';

    /** Returns {@see self::DE} or {@see self::EN}. Never throws. */
    public static function current(): string
    {
        try {
            $tag = Shop::getCurAdminLangTag();
        } catch (Throwable) {
            $tag = null;
        }
        if (!\is_string($tag) || $tag === '') {
            $tag = \is_string($_SESSION['AdminAccount']->language ?? null)
                ? $_SESSION['AdminAccount']->language
                : '';
        }

        return \str_starts_with(\strtolower($tag), 'en') ? self::EN : self::DE;
    }

    /**
     * @param array{de: string, en: string} $texts
     */
    public static function pick(array $texts, ?string $language = null): string
    {
        return ($language ?? self::current()) === self::EN ? $texts['en'] : $texts['de'];
    }
}
