<?php

declare(strict_types=1);

namespace Plugin\tnt_mcp\src\Mcp\Mode;

use JTL\DB\DbInterface;
use Throwable;

/**
 * Reads the merchant's `mode` plugin setting from the shop DB and maps it to a {@see Mode}.
 *
 * The setting is declared in info.xml (`<Settingslink>`) with ValueName {@see ModeSetting::VALUE_NAME}
 * and is stored by JTL in `tplugineinstellungen` keyed by the plugin's numeric id. We join through
 * `tplugin` on the stable string PluginID so no numeric id has to be threaded into the endpoint.
 *
 * Fail-safe: any error, missing row, or unexpected value resolves to the SAFE {@see Mode::Limited}.
 */
final class ModeSetting
{
    /** info.xml <ValueName> of the mode setting; also its `cName` in tplugineinstellungen. */
    public const VALUE_NAME = 'tnt_mcp_mode';

    /** Stable string PluginID (info.xml <PluginID>). */
    private const PLUGIN_ID = 'tnt_mcp';

    public static function fromDb(DbInterface $db): Mode
    {
        try {
            $row = $db->getSingleObject(
                'SELECT e.cWert AS v
                   FROM tplugineinstellungen e
                   INNER JOIN tplugin p ON p.kPlugin = e.kPlugin
                  WHERE p.cPluginID = :pid AND e.cName = :n',
                ['pid' => self::PLUGIN_ID, 'n' => self::VALUE_NAME],
            );
        } catch (Throwable) {
            return Mode::Limited;
        }

        $raw = ($row !== null && \is_string($row->v ?? null)) ? $row->v : null;

        return Mode::fromConfig($raw);
    }
}
