function generateFastifyServiceRoutes(context) {
  const { service } = context;
  if (!service) {
    throw new Error("Service is required in template context");
  }
  const serviceName = service.name;
  if (!serviceName) {
    throw new Error("Service must have a name");
  }
  const operationEntries = Array.isArray(service.operations) ? service.operations.map((op) => [op.name, op]) : Object.entries(service.operations || {});
  if (operationEntries.length === 0) {
    return `/**
 * ${serviceName} \u2014 no operations declared, no routes generated.
 */
import type { FastifyInstance } from 'fastify';

export default async function ${serviceName}Routes(_fastify: FastifyInstance, _options: any) {
  // No operations declared on ${serviceName}.
}
`;
  }
  const routeHandlers = operationEntries.map(([opName, op]) => generateOperationRoute(opName, op, serviceName)).join("\n\n");
  return `import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';

/**
 * ${serviceName} Routes
 *
 * Generated from SpecVerse specification \u2014 exposes service operations
 * as HTTP endpoints under /api/services/${serviceName}/.
 *
 * Operations: ${operationEntries.map(([n]) => n).join(", ")}
 */
export default async function ${serviceName}Routes(
  fastify: FastifyInstance,
  options: any
) {
  const service = options.services.${serviceName};
  if (!service) {
    throw new Error('Service ${serviceName} not registered in options.services');
  }

${routeHandlers.split("\n").map((line) => "  " + line).join("\n")}
}
`;
}
function generateOperationRoute(opName, op, serviceName) {
  const params = op?.parameters || {};
  const paramNames = Object.keys(params);
  const validations = [];
  for (const [pName, pDef] of Object.entries(params)) {
    const required = typeof pDef === "string" ? pDef.includes("required") : pDef?.required;
    const typeStr = typeof pDef === "string" ? pDef.split(" ")[0] : pDef?.type || "String";
    if (required) {
      validations.push(`  if (body.${pName} === undefined || body.${pName} === null) errors.push({ field: '${pName}', message: '${pName} is required' });`);
    }
    if (typeStr === "UUID" || typeStr === "String" || typeStr === "Email") {
      validations.push(`  if (body.${pName} !== undefined && typeof body.${pName} !== 'string') errors.push({ field: '${pName}', message: '${pName} must be a string' });`);
    } else if (typeStr === "Integer" || typeStr === "Number" || typeStr === "Float") {
      validations.push(`  if (body.${pName} !== undefined && typeof body.${pName} !== 'number') errors.push({ field: '${pName}', message: '${pName} must be a number' });`);
    } else if (typeStr === "Boolean") {
      validations.push(`  if (body.${pName} !== undefined && typeof body.${pName} !== 'boolean') errors.push({ field: '${pName}', message: '${pName} must be a boolean' });`);
    }
  }
  const validationBlock = validations.length > 0 ? `  const errors: Array<{ field: string; message: string }> = [];
${validations.join("\n")}
  if (errors.length > 0) return reply.status(400).send({ error: 'Validation failed', details: errors });` : "";
  const callExpression = paramNames.length > 0 ? `service.${opName}(${paramNames.map((p) => `body.${p}`).join(", ")})` : `service.${opName}(body)`;
  return `// ${opName}${op?.description ? ` \u2014 ${op.description}` : ""}
fastify.post('/${opName}', {
  handler: async (request: FastifyRequest, reply: FastifyReply) => {
    try {
      const body = (request.body || {}) as Record<string, any>;
${validationBlock}
      const result = await ${callExpression};
      return reply.send(result ?? { success: true });
    } catch (error) {
      return reply.status(400).send({
        error: 'Failed to execute ${serviceName}.${opName}',
        message: error instanceof Error ? error.message : String(error)
      });
    }
  }
});`;
}
export {
  generateFastifyServiceRoutes as default
};
