from __future__ import annotations from fastapi import APIRouter, Depends, HTTPException, Query from app.core.config import settings from app.db.store import Store from app.models.schemas.grow_event import GrowEventCreate, GrowEventOut router = APIRouter() def _get_store() -> Store: s = Store(settings.DB_PATH) try: yield s finally: s.close() @router.post("", response_model=GrowEventOut, status_code=201) async def create_grow_event(body: GrowEventCreate, store: Store = Depends(_get_store)): plant = store.conn.execute( "SELECT id FROM plants WHERE id = ?", (body.plant_id,) ).fetchone() if not plant: raise HTTPException(status_code=404, detail="Plant not found") cur = store.conn.execute( """INSERT INTO grow_events (plant_id, event_type, event_date, value_num, value_unit, note, photo_path) VALUES (?, ?, ?, ?, ?, ?, ?) RETURNING *""", ( body.plant_id, body.event_type, body.event_date, body.value_num, body.value_unit, body.note, body.photo_path, ), ) row = store._row_to_dict(cur.fetchone()) store.conn.commit() return row @router.get("", response_model=list[GrowEventOut]) async def list_grow_events( plant_id: int = Query(..., description="Plant ID to filter events"), store: Store = Depends(_get_store), ): rows = store.conn.execute( "SELECT * FROM grow_events WHERE plant_id = ? ORDER BY event_date DESC", (plant_id,), ).fetchall() return [store._row_to_dict(r) for r in rows]