<?php

declare(strict_types=1);

namespace Plugin\tnt_mcp\src\Mcp\OAuth;

use JTL\Backend\AdminTemplate;
use JTL\Shop;
use Throwable;

/**
 * Pulls the shop's own branding (name, logo, admin stylesheet) so the OAuth authorize/consent
 * screen looks like it belongs to this shop's backend rather than a generic plugin page — same
 * visual reference as admin/templates/bootstrap/login.tpl (logo above a centered card, admin CSS
 * bundle for colors/fonts/spacing).
 *
 * Every lookup is defensive: this page must never 500 just because a shop setting is missing or
 * the admin template cache isn't warm, and it must also stay safe to call from contexts where the
 * full JTL container isn't wired (e.g. unit tests) — any failure degrades to a plain, still-usable
 * consent screen instead of crashing the OAuth flow.
 */
final class ConsentBranding
{
    /** Shop name shown on the card, e.g. "Musterschop GmbH". Falls back to a generic label. */
    public static function shopName(): string
    {
        try {
            $name = Shop::getSettingValue(\CONF_GLOBAL, 'global_shopname');
            if (\is_string($name) && \trim($name) !== '') {
                return \trim($name);
            }
        } catch (Throwable) {
            // fall through to default below
        }

        return 'JTL-Shop';
    }

    /**
     * Full URL of the shop's uploaded admin/shop logo (same source as Shop::getLogo(), which
     * backs the "shop logo" admin/includes/src/Router/Controller/Backend/LogoController.php
     * upload feature), or null when no custom logo has been uploaded — the template then falls
     * back to a text-only header instead of guessing an image path.
     */
    public static function logoUrl(): ?string
    {
        try {
            $url = Shop::getLogo(true);

            return ($url !== null && $url !== '') ? $url : null;
        } catch (Throwable) {
            return null;
        }
    }

    /**
     * `<link>`/`<script>` tags for the exact same minified admin CSS/JS bundle the backend login
     * screen loads (see admin/templates/bootstrap/tpl_inc/header.tpl:13-14, assigned from
     * JTL\Backend\AdminTemplate::getResources() via includes/src/Smarty/BackendSmarty.php:88-89).
     * Reusing the real bundle — instead of hand-copying colors — means the consent screen tracks
     * the shop's active admin theme/branding automatically. Returns an empty string if the admin
     * template system can't be reached (e.g. no DB/container available), in which case the
     * template's own minimal inline fallback styles take over.
     */
    public static function adminStyleTags(): string
    {
        try {
            $resources = AdminTemplate::getInstance()->getResources(true);

            return $resources['css'];
        } catch (Throwable) {
            return '';
        }
    }
}
