import { z } from 'zod';
import { registerTool } from '../tools/registry.js';
import { telemetryQuery, telemetryClusters, telemetryMetrics } from '../../lib/platform-client.js';
import { config } from '../../lib/config.js';
import type { McpToolRequest } from '../tools/types.js';

const tokenOf = (req: McpToolRequest) => req.headers.authorization?.slice(7);

registerTool({
  name: 'platform.telemetry.query',
  description:
    'Query raw telemetry events for a product. Returns paginated event list. Requires admin role.',
  requiredRole: 'admin',
  inputSchema: z.object({
    productId: z.string().min(1).describe('Product ID to scope the query'),
    eventType: z.string().optional().describe('Filter by event type'),
    from: z.string().optional().describe('ISO 8601 start time'),
    to: z.string().optional().describe('ISO 8601 end time'),
    limit: z.coerce.number().min(1).max(config.QUERY_MAX_LIMIT).optional().describe('Page size'),
    continuationToken: z.string().optional().describe('Pagination cursor from previous response'),
  }),
  async execute(args, req) {
    return telemetryQuery(args, {
      token: tokenOf(req),
      requestId: req.id,
      productId: args.productId,
    });
  },
});

registerTool({
  name: 'platform.telemetry.clusters',
  description:
    'Get error clusters (fingerprinted error groups) for a product. Requires admin role.',
  requiredRole: 'admin',
  inputSchema: z.object({
    productId: z.string().min(1).describe('Product ID to scope the query'),
    from: z.string().optional().describe('ISO 8601 start time'),
    to: z.string().optional().describe('ISO 8601 end time'),
  }),
  async execute(args, req) {
    return telemetryClusters(
      { from: args.from, to: args.to },
      { token: tokenOf(req), requestId: req.id, productId: args.productId }
    );
  },
});

registerTool({
  name: 'platform.telemetry.metrics',
  description: 'Get ingestion metrics for the telemetry pipeline. Requires admin role.',
  requiredRole: 'admin',
  inputSchema: z.object({}),
  async execute(_args, req) {
    return telemetryMetrics({
      token: tokenOf(req),
      requestId: req.id,
    });
  },
});
