from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form from sqlalchemy.orm import Session from app.api.dependencies import get_db from app.models.user import User from app.schemas.userupdate import UserUpdate from app.s3_utils import upload_image_to_s3 router = APIRouter() @router.patch("/userupdate/{username}", response_model=UserUpdate) async def update_user_profile( username: str, bio: str = Form(None), profile_picture: UploadFile = File(None), add_follower: str = Form(None), add_following: str = Form(None), db: Session = Depends(get_db), ): user = db.query(User).filter(User.username == username).first() if not user: raise HTTPException(status_code=404, detail="User not found") if bio is not None: user.bio = bio if profile_picture: s3_url = upload_image_to_s3(profile_picture, profile_picture.filename) user.profile_picture = s3_url if add_follower: follower_user = db.query(User).filter(User.username == add_follower).first() if not follower_user: raise HTTPException(status_code=404, detail="Follower user not found") if add_follower not in user.followers: user.followers.append(add_follower) if username not in follower_user.following: follower_user.following.append(username) if add_following: following_user = db.query(User).filter(User.username == add_following).first() if not following_user: raise HTTPException(status_code=404, detail="Following user not found") if add_following not in user.following: user.following.append(add_following) if username not in following_user.followers: following_user.followers.append(username) db.commit() db.refresh(user) return user @router.patch("/userupdate/{username}/unfollow", response_model=UserUpdate) async def unfollow_user( username: str, unfollow_username: str = Form(...), db: Session = Depends(get_db), ): user = db.query(User).filter(User.username == username).first() if not user: raise HTTPException(status_code=404, detail="User not found") unfollow_user = db.query(User).filter(User.username == unfollow_username).first() if not unfollow_user: raise HTTPException(status_code=404, detail="User to unfollow not found") if unfollow_username in user.following: user.following.remove(unfollow_username) if username in unfollow_user.followers: unfollow_user.followers.remove(username) db.commit() db.refresh(user) return user