from __future__ import annotations from fastapi import APIRouter, Depends, HTTPException from app.core.config import settings from app.db.store import Store from app.models.schemas.location import LocationCreate, LocationOut, LocationUpdate router = APIRouter() def _get_store() -> Store: s = Store(settings.DB_PATH) try: yield s finally: s.close() @router.post("", response_model=LocationOut, status_code=201) async def create_location(body: LocationCreate, store: Store = Depends(_get_store)): cur = store.conn.execute( """INSERT INTO locations (name, kind, size_note, sun_note, notes) VALUES (?, ?, ?, ?, ?) RETURNING *""", (body.name, body.kind, body.size_note, body.sun_note, body.notes), ) row = store._row_to_dict(cur.fetchone()) store.conn.commit() return row @router.get("", response_model=list[LocationOut]) async def list_locations(store: Store = Depends(_get_store)): rows = store.conn.execute("SELECT * FROM locations ORDER BY name").fetchall() return [store._row_to_dict(r) for r in rows] @router.get("/{location_id}", response_model=LocationOut) async def get_location(location_id: int, store: Store = Depends(_get_store)): row = store.conn.execute( "SELECT * FROM locations WHERE id = ?", (location_id,) ).fetchone() if not row: raise HTTPException(status_code=404, detail="Location not found") return store._row_to_dict(row) @router.delete("/{location_id}", status_code=204) async def delete_location(location_id: int, store: Store = Depends(_get_store)): store.conn.execute("DELETE FROM locations WHERE id = ?", (location_id,)) store.conn.commit()