<?php

declare(strict_types=1);

namespace Plugin\tnt_mcp\src\Mcp\Admin;

use JTL\DB\DbInterface;
use JTL\Shop;
use Throwable;

/**
 * An absolute link into one of this plugin's admin tabs, for a reader who is not in the admin.
 *
 * {@see TabUrl} builds the relative links the tabs use on each other; those are worthless to an MCP
 * client, which has to hand the merchant something they can paste into a browser.
 *
 * ⚠️ The backend route is `/admin/plugin/{id}` where `{id}` is the NUMERIC `kPlugin`
 * ({@see \JTL\Router\Controller\Backend\PluginController} casts it to int) — the stable string
 * PluginID in the path resolves to 0 and renders "Plugin wurde nicht gefunden". So the id has to be
 * looked up, which is the only reason this class needs a database at all. The tab is then selected
 * with `cPluginTab`, which does take the tab's NAME.
 *
 * Returns `''` when either half cannot be resolved — a caller must then omit the link rather than
 * emit a broken one, because a dead URL in a chat window is worse than a sentence naming the menu
 * path.
 */
final class PluginAdminUrl
{
    /** Stable string PluginID (info.xml <PluginID>). */
    private const PLUGIN_ID = 'tnt_mcp';

    /**
     * @param array<string,string> $query extra parameters, e.g. a setup token
     * @param DbInterface|null     $db    injected by tests; production resolves the shop container
     */
    public static function tab(string $tabName, array $query = [], ?DbInterface $db = null): string
    {
        try {
            $base     = \rtrim(Shop::getAdminURL(), '/');
            $db     ??= Shop::Container()->getDB();
            $row      = $db->getSingleObject(
                'SELECT `kPlugin` FROM `tplugin` WHERE `cPluginID` = :pid',
                ['pid' => self::PLUGIN_ID]
            );
        } catch (Throwable) {
            return '';
        }

        $kPlugin = (int)($row->kPlugin ?? 0);
        if ($base === '' || $kPlugin <= 0) {
            return '';
        }

        if ($tabName !== '') {
            $query['cPluginTab'] = $tabName;
        }

        $url = $base . '/plugin/' . $kPlugin;

        return $query === [] ? $url : $url . '?' . \http_build_query($query);
    }
}
