import type { rejectionError } from "../errors"
import logging from "../logging"
import type { NextApiRequest, NextApiResponse } from "next"

export interface API<T> {
  req: NextApiRequest
  res: NextApiResponse<T>
}

export default function sendError<T>(
  context: API<T>,
  err: rejectionError | Error
) {
  const { res, req } = context
  // If something went wrong, let the client know with status 500
  res.status("statusCode" in err ? err.statusCode : 500).end()
  logging(
    err.message,
    "type" in err && err.type
      ? [err.type]
      : ["solved" in err && err.solved ? "debug" : "error"],
    req
  )
  if ("name" in err) console.log(err)
}
