import { supabase } from "@/integrations/supabase/client";

const BUCKET = "mold-photos";

/** Create a temporary viewing link for a private storage path. */
export async function signedUrl(path?: string | null, expiresIn = 3600) {
  if (!path) return null;
  if (path.startsWith("http") || path.startsWith("data:")) return path;
  const { data } = await supabase.storage.from(BUCKET).createSignedUrl(path, expiresIn);
  return data?.signedUrl ?? null;
}

export async function signedUrls(paths: (string | null | undefined)[]) {
  const out = await Promise.all(paths.map((p) => signedUrl(p)));
  return out.filter((u): u is string => Boolean(u));
}

export async function uploadToBucket(file: File, folder: string, userId: string) {
  const safe = file.name.replace(/[^\w.-]/g, "");
  const path = `${userId}/${folder}/${crypto.randomUUID()}-${safe}`;
  const { error } = await supabase.storage.from(BUCKET).upload(path, file);
  if (error) throw error;
  return path;
}