<?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\OrderReader;
use Plugin\tnt_mcp\src\Mcp\Contracts\Tool;
use Plugin\tnt_mcp\src\Mcp\Mode\EndpointClass;

/**
 * READ tool: the order book for a time window, newest first, with window-wide totals on top.
 *
 * The totals are why this is a tool and not a documented `SELECT * FROM tbestellung`: the caller
 * asked "how is the shop doing", and a bare page of rows answers "here are 20 lines". The status
 * names ({@see \Plugin\tnt_mcp\src\Mcp\Analytics\OrderStatus}) are the other half — `cStatus` is a
 * `char(2)` whose values mean nothing to a reader who has not memorised `defines_inc.php`.
 */
final class ListOrders implements Tool
{
    private const ARGS = ['since', 'until', 'status', 'customerId', 'limit', 'offset'];

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

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

    public function description(): string
    {
        return 'List orders in a time window, newest first, with totals, revenue and a status '
            . 'breakdown for the whole window.';
    }

    /** @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)()->orders($query);

        $result['notes'] = $query->notes;

        return $result;
    }
}
