import { slugify } from "@menulio/shared";
import { supabase } from "./supabase.js";

export async function generateUniqueRestaurantSlug(name: string): Promise<string> {
  if (!supabase) throw new Error("supabase not configured");

  const base = slugify(name) || "restoran";

  for (let attempt = 0; attempt < 30; attempt++) {
    const candidate = attempt === 0 ? base : `${base}-${attempt + 1}`;
    const { data, error } = await supabase
      .from("restaurants")
      .select("id")
      .eq("slug", candidate)
      .maybeSingle();

    if (!error && !data) return candidate;
  }

  return `${base}-${Date.now()}`;
}
