from fastapi import APIRouter, Depends, HTTPException from sqlalchemy import case from sqlalchemy.orm import Session, joinedload from typing import List from auth import get_current_user from database import get_db from models import Batch, User, Variety from schemas import BatchCreate, BatchOut, BatchUpdate router = APIRouter(prefix="/batches", tags=["batches"]) @router.get("/", response_model=List[BatchOut]) def list_batches(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): return ( db.query(Batch) .options(joinedload(Batch.variety)) .filter(Batch.user_id == current_user.id) .order_by(case((Batch.sow_date.is_(None), 1), else_=0), Batch.sow_date.desc(), Batch.created_at.desc()) .all() ) @router.get("/{batch_id}", response_model=BatchOut) def get_batch(batch_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): b = db.query(Batch).options(joinedload(Batch.variety)).filter(Batch.id == batch_id, Batch.user_id == current_user.id).first() if not b: raise HTTPException(status_code=404, detail="Batch not found") return b @router.post("/", response_model=BatchOut, status_code=201) def create_batch(data: BatchCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): if not db.query(Variety).filter(Variety.id == data.variety_id, Variety.user_id == current_user.id).first(): raise HTTPException(status_code=404, detail="Variety not found") b = Batch(**data.model_dump(), user_id=current_user.id) db.add(b) db.commit() db.refresh(b) return db.query(Batch).options(joinedload(Batch.variety)).filter(Batch.id == b.id).first() @router.put("/{batch_id}", response_model=BatchOut) def update_batch(batch_id: int, data: BatchUpdate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): b = db.query(Batch).filter(Batch.id == batch_id, Batch.user_id == current_user.id).first() if not b: raise HTTPException(status_code=404, detail="Batch not found") for field, value in data.model_dump().items(): setattr(b, field, value) db.commit() db.refresh(b) return db.query(Batch).options(joinedload(Batch.variety)).filter(Batch.id == b.id).first() @router.delete("/{batch_id}", status_code=204) def delete_batch(batch_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): b = db.query(Batch).filter(Batch.id == batch_id, Batch.user_id == current_user.id).first() if not b: raise HTTPException(status_code=404, detail="Batch not found") db.delete(b) db.commit()