import { NextResponse } from "next/server";
import type { ErrorResponseBody } from "./errors";
import { toHttpError } from "./errors";

export function ok<T>(data: T, init?: ResponseInit) {
  return NextResponse.json(data, { status: 200, ...init });
}

export function created<T>(data: T, init?: ResponseInit) {
  return NextResponse.json(data, { status: 201, ...init });
}

export function noContent() {
  return new NextResponse(null, { status: 204 });
}

export function errorResponse(err: unknown) {
  const httpErr = toHttpError(err);
  const body: ErrorResponseBody = {
    error: {
      message: httpErr.message,
      code: httpErr.code,
      details: httpErr.details,
    },
  };
  return NextResponse.json(body, { status: httpErr.status });
}
