import { requireRestaurantMember } from "./auth.js";
import { supabase } from "./supabase.js";

export async function getMenuIfMember(userId: string, menuId: string) {
  if (!supabase) return null;

  const { data: menu } = await supabase
    .from("menus")
    .select("*, locations(restaurant_id)")
    .eq("id", menuId)
    .single();

  if (!menu) return null;

  const restaurantId = (menu as { locations: { restaurant_id: string } }).locations.restaurant_id;
  const isMember = await requireRestaurantMember(userId, restaurantId);
  if (!isMember) return null;

  return { menu, restaurantId };
}

export async function getCategoryIfMember(userId: string, categoryId: string) {
  if (!supabase) return null;

  const { data: category } = await supabase
    .from("menu_categories")
    .select("*")
    .eq("id", categoryId)
    .single();

  if (!category) return null;

  const access = await getMenuIfMember(userId, category.menu_id as string);
  if (!access) return null;

  return { category, ...access };
}

export async function getItemIfMember(userId: string, itemId: string) {
  if (!supabase) return null;

  const { data: item } = await supabase.from("menu_items").select("*").eq("id", itemId).single();
  if (!item) return null;

  const access = await getCategoryIfMember(userId, item.category_id as string);
  if (!access) return null;

  return { item, ...access };
}
