import { Id } from "./_generated/dataModel";

// Change this if your public IP changes
const PUBLIC_CONVEX_URL = "https://api.brycord.com";

/** Rewrite any URL to use the public hostname/port/protocol */
export function rewriteToPublicUrl(url: string): string {
  try {
    const original = new URL(url);
    const target = new URL(PUBLIC_CONVEX_URL);
    original.hostname = target.hostname;
    original.port = target.port;
    original.protocol = target.protocol;
    return original.toString();
  } catch {
    return url;
  }
}

/** Get a storage file URL rewritten to the public address */
export async function getPublicStorageUrl(
  ctx: { storage: { getUrl: (id: Id<"_storage">) => Promise<string | null> } },
  storageId: Id<"_storage">
): Promise<string | null> {
  const url = await ctx.storage.getUrl(storageId);
  if (!url) return null;
  return rewriteToPublicUrl(url);
}
