from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app import schemas, crud, database
from typing import List

router = APIRouter(prefix="/waiters", tags=["waiters"])

def get_db():
    db = database.SessionLocal()
    try:
        yield db
    finally:
        db.close()

@router.post("/", response_model=schemas.WaiterOut)
def create_waiter(waiter: schemas.WaiterCreate, db: Session = Depends(get_db)):
    return crud.create_waiter(db, waiter)

@router.get("/", response_model=List[schemas.WaiterOut])
def list_waiters(db: Session = Depends(get_db)):
    return crud.get_waiters(db)

@router.delete("/{waiter_id}")
def delete_waiter(waiter_id: int, db: Session = Depends(get_db)):
    waiter = db.query(crud.models.Waiter).filter(crud.models.Waiter.id == waiter_id).first()
    if not waiter:
        raise HTTPException(status_code=404, detail="Waiter not found")
    crud.delete_waiter(db, waiter_id)
    return {"detail": f"Waiter {waiter_id} deleted"}

@router.put("/{waiter_id}/")
def update_waiter_load(waiter_id: int, waiter: dict, db: Session = Depends(get_db)):
    # Solo permite actualizar el campo load
    new_load = waiter.get("load")
    if new_load is None:
        raise HTTPException(status_code=400, detail="Missing 'load' in request body")
    updated = crud.update_waiter_load(db, waiter_id, new_load)
    if not updated:
        raise HTTPException(status_code=404, detail="Waiter not found")
    return updated
