from fastapi import APIRouter, Depends, HTTPException, status from pydantic import BaseModel from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import select from app.dependencies import get_db, get_current_user from app.models.morning_routine import MorningRoutineItem from app.models.user import User router = APIRouter(prefix="/api/morning-routine", tags=["morning-routine"]) class MorningRoutineItemOut(BaseModel): id: int text: str order_index: int model_config = {"from_attributes": True} class MorningRoutineItemCreate(BaseModel): text: str order_index: int = 0 class MorningRoutineItemUpdate(BaseModel): text: str | None = None order_index: int | None = None @router.get("", response_model=list[MorningRoutineItemOut]) async def list_items( current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db), ): result = await db.execute( select(MorningRoutineItem) .where(MorningRoutineItem.user_id == current_user.id) .order_by(MorningRoutineItem.order_index, MorningRoutineItem.id) ) return result.scalars().all() @router.post("", response_model=MorningRoutineItemOut, status_code=status.HTTP_201_CREATED) async def create_item( body: MorningRoutineItemCreate, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db), ): item = MorningRoutineItem(user_id=current_user.id, text=body.text, order_index=body.order_index) db.add(item) await db.commit() await db.refresh(item) return item @router.patch("/{item_id}", response_model=MorningRoutineItemOut) async def update_item( item_id: int, body: MorningRoutineItemUpdate, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db), ): result = await db.execute( select(MorningRoutineItem).where( MorningRoutineItem.id == item_id, MorningRoutineItem.user_id == current_user.id, ) ) item = result.scalar_one_or_none() if not item: raise HTTPException(status_code=404, detail="Item not found") if body.text is not None: item.text = body.text if body.order_index is not None: item.order_index = body.order_index await db.commit() await db.refresh(item) return item @router.delete("/{item_id}", status_code=status.HTTP_204_NO_CONTENT) async def delete_item( item_id: int, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db), ): result = await db.execute( select(MorningRoutineItem).where( MorningRoutineItem.id == item_id, MorningRoutineItem.user_id == current_user.id, ) ) item = result.scalar_one_or_none() if not item: raise HTTPException(status_code=404, detail="Item not found") await db.delete(item) await db.commit()