import { ConvexHttpClient } from "convex/browser"

import { env } from "@/lib/env"
import { DEFAULT_CONVEX_URL } from "@/lib/constants"

export class ConvexConfigurationError extends Error {
  constructor(message = "Convex não configurado.") {
    super(message)
    this.name = "ConvexConfigurationError"
  }
}

function isServerSide() {
  return typeof window === "undefined"
}

export function requireConvexUrl(): string {
  const url = isServerSide()
    ? env.CONVEX_INTERNAL_URL ?? env.NEXT_PUBLIC_CONVEX_URL ?? DEFAULT_CONVEX_URL
    : env.NEXT_PUBLIC_CONVEX_URL ?? DEFAULT_CONVEX_URL
  if (!url) {
    throw new ConvexConfigurationError()
  }
  return url
}

export function createConvexClient(): ConvexHttpClient {
  const url = requireConvexUrl()
  return new ConvexHttpClient(url)
}
