import { supabase } from "./supabase";

export const BUCKET_NAME = "restaurant-assets";

export type AssetFolder = "logos" | "covers" | "items";

/**
 * Uploads an image file (logo, cover banner, item photo) to Supabase Storage
 * and returns the public CDN URL.
 */
export async function uploadImageToSupabase(
  fileUri: string,
  folder: AssetFolder = "items"
): Promise<string> {
  const response = await fetch(fileUri);
  const blob = await response.blob();
  const fileExt = fileUri.split(".").pop()?.toLowerCase() || "jpg";
  const fileName = `${folder}/${Date.now()}-${Math.random().toString(36).substring(2, 9)}.${fileExt}`;

  const { data, error } = await supabase.storage
    .from(BUCKET_NAME)
    .upload(fileName, blob, {
      contentType: `image/${fileExt === "png" ? "png" : "jpeg"}`,
      upsert: true,
    });

  if (error) {
    throw new Error(`Resim yükleme hatası: ${error.message}`);
  }

  const { data: publicUrlData } = supabase.storage
    .from(BUCKET_NAME)
    .getPublicUrl(data.path);

  return publicUrlData.publicUrl;
}
