import random import string from fastapi import APIRouter, HTTPException, Request from config.database import get_supabase_admin from middleware.auth_guard import get_current_user router = APIRouter(prefix="/api/share", tags=["share"]) def _generate_code(length=8) -> str: return ''.join(random.choices(string.ascii_letters + string.digits, k=length)) @router.post("/create") async def create_share(request: Request): user = await get_current_user(request) body = await request.json() analysis_id = body.get("analysis_id") if not analysis_id: raise HTTPException(status_code=400, detail="analysis_id is required") db = get_supabase_admin() # Verify the analysis belongs to this user analysis = db.table("analyses").select("id").eq("id", analysis_id).eq("user_id", str(user.id)).single().execute() if not analysis.data: raise HTTPException(status_code=404, detail="Analysis not found") # Generate unique short code for _ in range(5): code = _generate_code() existing = db.table("shared_analyses").select("id").eq("short_code", code).execute() if not existing.data: break result = db.table("shared_analyses").insert({ "analysis_id": analysis_id, "short_code": code, "is_public": True, }).execute() return {"short_code": code, "url": f"https://codenexus.qzz.io/share/{code}"} @router.get("/{code}") async def get_shared_analysis(code: str): db = get_supabase_admin() shared = db.table("shared_analyses").select("*, analyses(*)").eq("short_code", code).eq("is_public", True).single().execute() if not shared.data: raise HTTPException(status_code=404, detail="Shared analysis not found or has been removed") return shared.data @router.delete("/{code}") async def delete_share(code: str, request: Request): user = await get_current_user(request) db = get_supabase_admin() shared = db.table("shared_analyses").select("*, analyses(user_id)").eq("short_code", code).single().execute() if not shared.data: raise HTTPException(status_code=404, detail="Share not found") if shared.data["analyses"]["user_id"] != str(user.id): raise HTTPException(status_code=403, detail="Not your share link") db.table("shared_analyses").delete().eq("short_code", code).execute() return {"message": "Share link deleted"}