from typing import List, Optional from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy.orm import Session from app.db.session import get_db from app.models.todo import Todo from app.schemas.todo import Todo as TodoSchema from app.schemas.todo import TodoCreate, TodoUpdate router = APIRouter() @router.get("/", response_model=List[TodoSchema]) def read_todos( skip: int = 0, limit: int = 100, completed: Optional[bool] = None, db: Session = Depends(get_db), ): """ Retrieve todos. """ query = db.query(Todo) if completed is not None: query = query.filter(Todo.completed == completed) todos = query.offset(skip).limit(limit).all() return todos @router.post("/", response_model=TodoSchema, status_code=status.HTTP_201_CREATED) def create_todo( todo_in: TodoCreate, db: Session = Depends(get_db), ): """ Create new todo. """ todo = Todo( title=todo_in.title, description=todo_in.description, completed=todo_in.completed, ) db.add(todo) db.commit() db.refresh(todo) return todo @router.get("/{todo_id}", response_model=TodoSchema) def read_todo( todo_id: int, db: Session = Depends(get_db), ): """ Get todo by ID. """ todo = db.query(Todo).filter(Todo.id == todo_id).first() if not todo: raise HTTPException(status_code=404, detail="Todo not found") return todo @router.put("/{todo_id}", response_model=TodoSchema) def update_todo( todo_id: int, todo_in: TodoUpdate, db: Session = Depends(get_db), ): """ Update a todo. """ todo = db.query(Todo).filter(Todo.id == todo_id).first() if not todo: raise HTTPException(status_code=404, detail="Todo not found") update_data = todo_in.dict(exclude_unset=True) for field, value in update_data.items(): setattr(todo, field, value) db.add(todo) db.commit() db.refresh(todo) return todo @router.delete("/{todo_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None) def delete_todo( todo_id: int, db: Session = Depends(get_db), ): """ Delete a todo. """ todo = db.query(Todo).filter(Todo.id == todo_id).first() if not todo: raise HTTPException(status_code=404, detail="Todo not found") db.delete(todo) db.commit() return None