import io import uuid from supabase import create_client from app.config import get_settings BUCKET = "product-images" def _client(): s = get_settings() return create_client(s.SUPABASE_URL, s.SUPABASE_SERVICE_ROLE_KEY) async def upload_product_image(product_id: str, file_bytes: bytes, content_type: str) -> dict: ext = "jpg" if "jpeg" in content_type else content_type.split("/")[-1] path = f"{product_id}/{uuid.uuid4()}.{ext}" client = _client() result = client.storage.from_(BUCKET).upload( path, file_bytes, {"content-type": content_type, "upsert": False}, ) # supabase-py v2 raises StorageException on failure, but guard against # unexpected response shapes that silently skip the upload if hasattr(result, "error") and result.error: raise RuntimeError(f"Storage upload failed: {result.error}") url = client.storage.from_(BUCKET).get_public_url(path) return {"url": url, "storage_path": path} async def delete_product_image(storage_path: str): _client().storage.from_(BUCKET).remove([storage_path])