import { NextResponse } from "next/server";
import { ZodError } from "zod";
import { APIError, ValidationError } from "./errors";

type RouteHandler = (req: Request, ...args: unknown[]) => Promise<Response>;

export function withErrorHandler<T extends RouteHandler>(handler: T): T {
  return (async (req: Request, ...args: unknown[]) => {
    try {
      return await handler(req, ...args);
    } catch (err) {
      if (err instanceof APIError) {
        return NextResponse.json(
          { error: err.message, ...(err.details ? { details: err.details } : {}) },
          { status: err.statusCode },
        );
      }
      if (err instanceof ZodError) {
        const ve = new ValidationError("Invalid request", {
          code: "VALIDATION_ERROR",
          fieldErrors: err.flatten().fieldErrors,
        });
        return NextResponse.json(
          { error: ve.message, details: ve.details },
          { status: 400 },
        );
      }
      console.error("[api] unhandled error in route handler:", err);
      return NextResponse.json({ error: "An unexpected error occurred" }, { status: 500 });
    }
  }) as T;
}
