import { ApiFormError } from "@/lib/api-form-error"
import type { CategoryErrorResponse } from "@/types/category-api"

/** Parses JSON error body and throws {@link ApiFormError} when `res` is not ok. */
export async function throwIfNotOk(res: Response): Promise<void> {
  if (res.ok) return
  let message = `Request failed (${res.status})`
  let fieldErrors: Record<string, string> | undefined
  try {
    const data = (await res.json()) as Partial<CategoryErrorResponse>
    if (typeof data.error === "string" && data.error) message = data.error
    if (data.fieldErrors && typeof data.fieldErrors === "object") fieldErrors = data.fieldErrors
  } catch {
    /* non-JSON body */
  }
  throw new ApiFormError(message, fieldErrors)
}
