import "server-only";

export type MediaErrorCode =
  | "invalid_input"
  | "invalid_file"
  | "path_safety_violation"
  | "ffmpeg_failure"
  | "ffprobe_failure"
  | "timeout"
  | "missing_binary"
  | "filesystem_failure"
  | "unknown";

export class MediaProcessingError extends Error {
  readonly code: MediaErrorCode;
  readonly statusCode: number;
  readonly details?: unknown;

  constructor({
    message,
    code,
    statusCode = 500,
    details
  }: {
    message: string;
    code: MediaErrorCode;
    statusCode?: number;
    details?: unknown;
  }) {
    super(message);
    this.name = "MediaProcessingError";
    this.code = code;
    this.statusCode = statusCode;
    this.details = details;
  }
}

export function asMediaProcessingError(error: unknown): MediaProcessingError {
  if (error instanceof MediaProcessingError) {
    return error;
  }

  if (error instanceof Error) {
    return new MediaProcessingError({
      message: error.message,
      code: "unknown",
      statusCode: 500
    });
  }

  return new MediaProcessingError({
    message: "Unknown media processing error.",
    code: "unknown",
    statusCode: 500
  });
}
