<?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: saved carts, what is in them, and how many never became an order.
 *
 * Two honesty constraints ship in the response rather than in a doc nobody reads: these are the
 * *persistent* carts of logged-in customers (guest carts live in the session and exist nowhere in
 * the database), and the cart rows carry no price, so the value is the article's current price
 * multiplied by the quantity — an estimate, and labelled one.
 */
final class CartStatistics implements Tool
{
    private const ARGS = ['since', 'until'];

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

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

    public function description(): string
    {
        return 'Saved customer carts in a window: count, items, estimated value, abandonment rate '
            . 'and the products most often left in them.';
    }

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

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

        return $result;
    }
}
