# app/crud/item.py from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.future import select from sqlalchemy import delete as sql_delete, update as sql_update # Use aliases from typing import Optional, List as PyList from datetime import datetime, timezone from app.models import Item as ItemModel from app.schemas.item import ItemCreate, ItemUpdate async def create_item(db: AsyncSession, item_in: ItemCreate, list_id: int, user_id: int) -> ItemModel: """Creates a new item record for a specific list.""" db_item = ItemModel( name=item_in.name, quantity=item_in.quantity, list_id=list_id, added_by_id=user_id, is_complete=False # Default on creation ) db.add(db_item) await db.commit() await db.refresh(db_item) return db_item async def get_items_by_list_id(db: AsyncSession, list_id: int) -> PyList[ItemModel]: """Gets all items belonging to a specific list, ordered by creation time.""" result = await db.execute( select(ItemModel) .where(ItemModel.list_id == list_id) .order_by(ItemModel.created_at.asc()) # Or desc() if preferred ) return result.scalars().all() async def get_item_by_id(db: AsyncSession, item_id: int) -> Optional[ItemModel]: """Gets a single item by its ID.""" result = await db.execute(select(ItemModel).where(ItemModel.id == item_id)) return result.scalars().first() async def update_item(db: AsyncSession, item_db: ItemModel, item_in: ItemUpdate, user_id: int) -> ItemModel: """Updates an existing item record.""" update_data = item_in.model_dump(exclude_unset=True) now_utc = datetime.now(timezone.utc) if 'is_complete' in update_data: if update_data['is_complete'] is True and item_db.completed_by_id is None: update_data['completed_by_id'] = user_id elif update_data['is_complete'] is False: update_data['completed_by_id'] = None if 'price' in update_data: if update_data['price'] is not None: update_data['price_added_by_id'] = user_id update_data['price_added_at'] = now_utc else: update_data['price_added_by_id'] = None update_data['price_added_at'] = None for key, value in update_data.items(): setattr(item_db, key, value) db.add(item_db) await db.commit() await db.refresh(item_db) return item_db async def delete_item(db: AsyncSession, item_db: ItemModel) -> None: """Deletes an item record.""" await db.delete(item_db) await db.commit() return None # Or return True/False