import type { FastifyError, FastifyReply, FastifyRequest } from 'fastify';
import { ZodError } from 'zod';

export interface ErrorResponse {
  error: string;
  statusCode: number;
  details?: unknown;
}

export function errorHandler(
  error: FastifyError,
  _request: FastifyRequest,
  reply: FastifyReply,
): void {
  // Zod validation errors
  if (error instanceof ZodError) {
    reply.code(400).send({
      error: 'Validation error',
      statusCode: 400,
      details: error.issues,
    } satisfies ErrorResponse);
    return;
  }

  // Fastify validation errors (from schema validation)
  if (error.validation !== undefined) {
    reply.code(400).send({
      error: 'Validation error',
      statusCode: 400,
      details: error.validation,
    } satisfies ErrorResponse);
    return;
  }

  // Rate limit exceeded
  if (error.statusCode === 429) {
    reply.code(429).send({
      error: 'Rate limit exceeded',
      statusCode: 429,
    } satisfies ErrorResponse);
    return;
  }

  // Known HTTP errors (includes service errors like NotFoundError, ConflictError)
  const statusCode = error.statusCode ?? 500;
  if (statusCode < 500) {
    reply.code(statusCode).send({
      error: error.message,
      statusCode,
    } satisfies ErrorResponse);
    return;
  }

  // Internal server errors — don't leak details
  reply.log.error(error);
  reply.code(500).send({
    error: 'Internal server error',
    statusCode: 500,
  } satisfies ErrorResponse);
}
