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

export class ApiError extends Error {
  constructor(
    public statusCode: number,
    public code: string,
    message: string,
    public details?: unknown[]
  ) {
    super(message);
    this.name = 'ApiError';
  }

  static badRequest(message: string, details?: unknown[]): ApiError {
    return new ApiError(400, 'BAD_REQUEST', message, details);
  }

  static validationError(details: unknown[]): ApiError {
    return new ApiError(400, 'VALIDATION_ERROR', 'Validierungsfehler', details);
  }

  static internalError(message: string = 'Interner Serverfehler'): ApiError {
    return new ApiError(500, 'INTERNAL_ERROR', message);
  }
}

export function errorHandler(
  error: FastifyError | ApiError | ZodError | Error,
  request: FastifyRequest,
  reply: FastifyReply
): void {
  request.log.error(error);

  if (error instanceof ZodError) {
    reply.status(400).send({
      error: 'VALIDATION_ERROR',
      message: 'Ungültige Eingabedaten',
      details: error.errors.map(e => ({
        path: e.path.join('.'),
        message: e.message,
      })),
    });
    return;
  }

  if (error instanceof ApiError) {
    reply.status(error.statusCode).send({
      error: error.code,
      message: error.message,
      details: error.details,
    });
    return;
  }

  // Unbekannter Fehler
  reply.status(500).send({
    error: 'INTERNAL_ERROR',
    message: 'Ein unerwarteter Fehler ist aufgetreten',
  });
}
