import { z } from 'zod';
import type { ToolDef } from '../../tools.js';
import { callCodecontext, type CodecontextResponse } from '../../codecontext_client.js';

export const GetMiddlewareInput = z.object({});
export type GetMiddlewareInputT = z.infer<typeof GetMiddlewareInput>;

const DESCRIPTION =
  'Detects middleware registrations in the project. Identifies auth, CORS, rate-limit, ' +
  'security-headers, error-handler, logging, and validation middleware by analyzing ' +
  'import names (@fastify/cors, helmet, etc.) and registration patterns ' +
  '(app.register, app.addHook, app.setErrorHandler).';

export async function executeGetMiddleware(
  _input: GetMiddlewareInputT,
  projectPath: string,
  fetcher: typeof fetch = fetch,
): Promise<CodecontextResponse> {
  return callCodecontext({ toolName: 'get_middleware', args: {}, projectPath }, fetcher);
}

export const getMiddleware: ToolDef<GetMiddlewareInputT> = {
  name: 'get_middleware',
  description: DESCRIPTION,
  inputSchema: GetMiddlewareInput,
  jsonSchema: {
    type: 'function',
    function: {
      name: 'get_middleware',
      description: DESCRIPTION,
      parameters: {
        type: 'object',
        properties: {},
        additionalProperties: false,
      },
    },
  },
  async execute(input, projectRoot) {
    return await executeGetMiddleware(input, projectRoot);
  },
};
