from fastapi import Depends, APIRouter, HTTPException, status from sqlalchemy.orm import Session from db.session import get_db from schemas.auction import ShowAuction, CreateAuction from typing import List from db.repository.auction import ( get_all_auctions, get_auction_by_id, create_new_auction, edit_auction_by_id, delete_auction_by_id, ) from db.models.user import User from apis.v1.route_auth import get_current_user router = APIRouter() @router.get("/", response_model=List[ShowAuction], status_code=status.HTTP_200_OK) def getAllAuctions( db: Session = Depends(get_db), current_user: User = Depends(get_current_user), ): auctions = get_all_auctions(db) return auctions @router.get("/{id}", response_model=ShowAuction, status_code=status.HTTP_200_OK) def getAuction( id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user), ): auction = get_auction_by_id(id, db) if auction is None: raise HTTPException( status_code=404, detail="Auction with this ID does not exist" ) return auction @router.post("/", status_code=status.HTTP_201_CREATED) def create_auction( auction: CreateAuction, db: Session = Depends(get_db), current_user: User = Depends(get_current_user), ): if current_user.Role != "Admin": raise HTTPException( status_code=403, detail="You are not authorized to perform this action" ) auction_res = create_new_auction(auction=auction, createId=current_user.Id, db=db) if auction_res == "novehicle": raise HTTPException( status_code=404, detail="Vehicle with this ID does not exist" ) elif auction_res == "vehicleunavailable": raise HTTPException( status_code=404, detail="Vehicle with this ID is currently not up for sale" ) return auction_res @router.patch("/{auc_id}", status_code=status.HTTP_200_OK) def editAuction( auc_id: int, auction: CreateAuction, db: Session = Depends(get_db), current_user: User = Depends(get_current_user), ): if current_user.Role != "Admin": raise HTTPException( status_code=403, detail="You are not authorized to perform this action" ) auction_res = edit_auction_by_id(id=auc_id, auction=auction, db=db) if auction_res == "noauction": raise HTTPException( status_code=404, detail="Auction with this ID does not exist" ) return auction_res @router.delete("/{auc_id}", status_code=status.HTTP_200_OK) def deleteAuction( auc_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user), ): if current_user.Role != "Admin": raise HTTPException( status_code=403, detail="You are not authorized to perform this action" ) auction_res = delete_auction_by_id(id=auc_id, db=db) if auction_res == "noauction": raise HTTPException( status_code=404, detail="Auction with this ID does not exist" ) return auction_res