import { NextRequest, NextResponse } from 'next/server';
import { ZodError } from 'zod';

export const validationErrorHandler =
  (handler: Function) =>
  async (req: NextRequest, ...args: any[]) => {
    try {
      return await handler(req, ...args);
    } catch (error) {
      if (error instanceof ZodError)
        return NextResponse.json({ message: error.format() }, { status: 400 });

      console.error(error);
      return NextResponse.json(
        { message: 'Server died for some reason' },
        { status: 500 },
      );
    }
  };
