""" File Upload API - Upload files to Supabase Storage """ from fastapi import APIRouter, Depends, UploadFile, File, HTTPException from uuid import UUID import time import logging from app.core.supabase import supabase_client from app.api.deps import get_current_user from app.models.user import User logger = logging.getLogger(__name__) router = APIRouter() @router.post("/file") async def upload_file( file: UploadFile = File(...), current_user: User = Depends(get_current_user) ): """ Upload a file to Supabase Storage. Returns public URL of uploaded file. """ if not supabase_client: raise HTTPException(status_code=500, detail="Storage not configured") # Validate file if not file.filename: raise HTTPException(status_code=400, detail="No filename") # Read file content content = await file.read() if len(content) > 10 * 1024 * 1024: # 10MB limit raise HTTPException(status_code=400, detail="File too large (max 10MB)") # Determine bucket based on content type content_type = file.content_type or "application/octet-stream" if content_type.startswith("image/"): bucket = "media" folder = "images" elif content_type == "application/pdf": bucket = "media" folder = "documents" elif content_type.startswith("video/"): bucket = "media" folder = "videos" else: bucket = "media" folder = "files" # Generate unique filename timestamp = int(time.time()) safe_filename = file.filename.replace(" ", "_") path = f"{current_user.tenant_id}/{folder}/{timestamp}_{safe_filename}" try: # Upload to Supabase Storage result = supabase_client.storage.from_(bucket).upload( path=path, file=content, file_options={"content-type": content_type} ) # Get public URL public_url = supabase_client.storage.from_(bucket).get_public_url(path) logger.info(f"✅ File uploaded: {path} -> {public_url[:60]}...") return { "ok": True, "url": public_url, "filename": file.filename, "content_type": content_type, "size": len(content) } except Exception as e: logger.error(f"❌ Upload failed: {e}") raise HTTPException(status_code=500, detail=f"Upload failed: {str(e)}") @router.post("/image") async def upload_image( file: UploadFile = File(...), current_user: User = Depends(get_current_user) ): """ Upload an image file. Validates that it's actually an image. """ if not file.content_type or not file.content_type.startswith("image/"): raise HTTPException(status_code=400, detail="File must be an image") return await upload_file(file, current_user) @router.post("/document") async def upload_document( file: UploadFile = File(...), current_user: User = Depends(get_current_user) ): """ Upload a document (PDF, DOC, etc). """ allowed_types = [ "application/pdf", "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ] if file.content_type not in allowed_types: raise HTTPException(status_code=400, detail="File must be PDF or DOC") return await upload_file(file, current_user)