<?php

declare(strict_types=1);

namespace Plugin\tnt_mcp\src\Mcp\Admin;

/**
 * Builds a link back to one specific tab of the plugin's backend page.
 *
 * The plugin's five tabs are panes of a single JTL page, selected client-side, so a self-link that
 * only carries its own parameter reloads the page on the *first* pane — the merchant presses
 * "Details", the plugin page appears to reload, and the card they asked for sits in a hidden pane.
 * `cPluginTab` is the shop's own remedy: `plugin_uebersicht.tpl:21` marks the pane active when it
 * equals the tab's name.
 *
 * Pure so it can be tested without a shop, a session or a Smarty instance.
 */
final class TabUrl
{
    /**
     * @param array<string, mixed>  $get       the current query string, normally `$_GET`
     * @param array<string, string> $overrides added or replaced; an empty-string value REMOVES the
     *        parameter, which is how a detail link turns back into a list link
     * @param string                $tabName   the Customlink name, e.g. 'Änderungen'; when empty
     *        the link is built without a tab hint rather than with a wrong one
     */
    public static function build(array $get, array $overrides = [], string $tabName = ''): string
    {
        $carried = \array_filter(
            $get,
            static fn (string $key): bool => $key !== 'cPluginTab' && !\array_key_exists($key, $overrides),
            \ARRAY_FILTER_USE_KEY,
        );

        $query = \array_filter(
            [...$carried, ...$overrides],
            static fn (mixed $value): bool => \is_scalar($value) && (string)$value !== '',
        );

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

        return '?' . \http_build_query($query);
    }
}
