<?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: revenue for a window, plus a time series the caller did not have to bucket itself.
 *
 * The granularity is chosen from the window's length rather than asked for — hour, day, week, month
 * — so "the last year" comes back as twelve rows instead of 365, and no call can return an
 * unbounded series. The chosen bucket is reported, because a model that assumes "day" while looking
 * at months would misread every number under it.
 */
final class SalesSummary implements Tool
{
    private const ARGS = ['since', 'until', 'status', 'customerId'];

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

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

    public function description(): string
    {
        return 'Revenue, order count and average order value for a window, with a time series and '
            . 'a breakdown by status and payment method.';
    }

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

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

        return $result;
    }
}
