import { NextResponse } from "next/server"
import { ZodError } from "zod"

function getStatus(error: unknown): number | null {
  if (typeof error !== "object" || error === null) return null
  const status = (error as Record<string, unknown>).status
  return typeof status === "number" ? status : null
}

function getMessage(error: unknown): string | null {
  if (error instanceof Error) return error.message
  if (typeof error !== "object" || error === null) return null
  const message = (error as Record<string, unknown>).message
  return typeof message === "string" ? message : null
}

export function withErrorHandling<TArgs extends unknown[]>(
  handler: (...args: TArgs) => Promise<Response>
) {
  return async (...args: TArgs): Promise<Response> => {
    try {
      return await handler(...args)
    } catch (error) {
      if (error instanceof ZodError) {
        return NextResponse.json(
          { error: "Validation failed", details: error.flatten() },
          { status: 400 }
        )
      }

      const status = getStatus(error) ?? 500
      const message = status >= 500 ? "Internal server error" : getMessage(error) ?? "Error"

      console.error("Unhandled API error:", error)
      return NextResponse.json({ error: message }, { status })
    }
  }
}

