<?php

declare(strict_types=1);

namespace Plugin\tnt_mcp\src\Mcp\Settings;

use JTL\DB\DbInterface;
use JTL\Shop;
use RuntimeException;

/**
 * Generic read side of the settings bridge: the YAML row IS the query. `conf` rows read the same
 * cached settings the shop itself reads ({@see Shop::getSettingValue()}); `list` rows run the
 * explicit column whitelist through {@see DbInterface::selectAll()} — the same shape the admin
 * controllers use (e.g. ShippingMethodsController, PaymentMethodsController). Zero per-setting
 * logic: every row is handled by exactly one of these two generic branches.
 */
final class SettingsReader
{
    public function __construct(private readonly DbInterface $db)
    {
    }

    public function read(SettingRow $row): mixed
    {
        if ($row->conf !== null) {
            return Shop::getSettingValue($row->conf->section, $row->conf->name);
        }
        if ($row->list !== null) {
            return $this->db->selectAll(
                $row->list->table,
                array_keys($row->list->where),
                array_values($row->list->where),
                implode(',', $row->list->fields),
                $row->list->order,
            );
        }

        throw new RuntimeException('setting "' . $row->key . '" declares neither conf nor list');
    }
}
