<?php

declare(strict_types=1);

namespace Plugin\tnt_mcp\src\Mcp\Tools;

use Closure;
use Plugin\tnt_mcp\src\Mcp\Analytics\AnalyticsQuery;
use Plugin\tnt_mcp\src\Mcp\Analytics\StatsReader;
use Plugin\tnt_mcp\src\Mcp\Contracts\Tool;
use Plugin\tnt_mcp\src\Mcp\Mode\EndpointClass;

/**
 * READ tool: what visitors typed into the shop search — and, more usefully, what came back empty.
 *
 * `withoutResults` is the list worth acting on: demand the catalogue did not answer. The counters
 * are lifetime totals (the shop keeps no per-day search history at all), which the response states
 * outright — reading `nAnzahlGesuche` as "searches this week" is the mistake this tool exists to
 * prevent.
 */
final class TopSearches implements Tool
{
    private const ARGS = ['since', 'until', 'limit'];

    /** @param Closure(): StatsReader $readerFactory must not touch the DB until run() */
    public function __construct(private readonly Closure $readerFactory)
    {
    }

    public function name(): string
    {
        return 'top_searches';
    }

    public function description(): string
    {
        return 'Most-used shop search terms and the terms that returned no results, with their '
            . 'lifetime search counts.';
    }

    /** @return array<string,mixed> */
    public function inputSchema(): array
    {
        return [
            'type'                 => 'object',
            'properties'           => AnalyticsQuery::schemaFor(self::ARGS),
            'additionalProperties' => false,
        ];
    }

    public function isWrite(): bool
    {
        return false;
    }

    public function scope(): string
    {
        return 'analytics:read';
    }

    public function endpointClass(): EndpointClass
    {
        return EndpointClass::Reversible;
    }

    /**
     * @param array<string,mixed> $args
     * @return array<string,mixed>
     */
    public function run(array $args): array
    {
        $query  = AnalyticsQuery::fromArgs($this->name(), $args, self::ARGS);
        $result = ($this->readerFactory)()->searches($query);

        $result['notes'] = \array_merge($query->notes, $result['notes']);

        return $result;
    }
}
