import { Response } from "express";

export function ok<T>(res: Response, data: T, message?: string) {
  return res.status(200).json({ data, ...(message ? { message } : {}) });
}

export function created<T>(res: Response, data: T, message?: string) {
  return res.status(201).json({ data, ...(message ? { message } : {}) });
}

export function noContent(res: Response) {
  return res.status(204).send();
}

export function handleError(
  res: Response,
  message: string,
  error: unknown,
  status = 500
) {
  const details =
    error && typeof error === "object" && "message" in error
      ? (error as any).message
      : String(error ?? "Unknown error");
  if (status >= 500) {
    // basic logging hook for server errors
    // eslint-disable-next-line no-console
    console.error("[Error]", message, details);
  }
  return res.status(status).json({ error: message, details });
}
