import "server-only";

import { asMediaProcessingError } from "@/lib/server/media-errors";

export interface ApiSuccessResponse<T> {
  ok: true;
  data: T;
}

export interface ApiErrorResponse {
  ok: false;
  error: {
    code: string;
    message: string;
  };
}

export function createSuccessResponse<T>(data: T, init?: ResponseInit) {
  return Response.json(
    {
      ok: true,
      data
    },
    init
  );
}

export function createErrorResponse(error: unknown, fallbackMessage = "Request failed.") {
  const resolvedError = asMediaProcessingError(error);
  const resolvedMessage = resolvedError.message?.trim();
  const normalizedMessage = resolvedMessage?.toLowerCase() || "";
  const safeMessage =
    !resolvedMessage || normalizedMessage === "error" || normalizedMessage === "internal server error"
      ? fallbackMessage
      : resolvedMessage;

  return Response.json(
    {
      ok: false,
      error: {
        code: resolvedError.code,
        message: safeMessage
      }
    },
    {
      status: resolvedError.statusCode
    }
  );
}
