from fastapi import APIRouter, Depends, HTTPException from psycopg import AsyncConnection from mm_api.db import get_conn from mm_api.models.location import LocationCreate, LocationRetype, LocationReparent, LocationSplitFrom, LocationMerge import mm_api.services.location as svc router = APIRouter(prefix="/locations", tags=["locations"]) @router.get("") async def list_locations(parent_id: int | None = None, conn: AsyncConnection = Depends(get_conn)): return await svc.list_children(conn, parent_id) @router.get("/{location_id}") async def get_location(location_id: int, conn: AsyncConnection = Depends(get_conn)): loc = await svc.get(conn, location_id) if not loc: raise HTTPException(404, "Lokasyon bulunamadı") return loc @router.post("", status_code=201) async def create_location(data: LocationCreate, conn: AsyncConnection = Depends(get_conn)): return await svc.create(conn, data) @router.patch("/{location_id}/retype") async def retype_location(location_id: int, data: LocationRetype, conn: AsyncConnection = Depends(get_conn)): loc = await svc.get(conn, location_id) if not loc: raise HTTPException(404, "Lokasyon bulunamadı") await svc.retype(conn, location_id, data) return await svc.get(conn, location_id) @router.patch("/{location_id}/reparent") async def reparent_location(location_id: int, data: LocationReparent, conn: AsyncConnection = Depends(get_conn)): loc = await svc.get(conn, location_id) if not loc: raise HTTPException(404, "Lokasyon bulunamadı") await svc.reparent(conn, location_id, data) return await svc.get(conn, location_id) @router.post("/{location_id}/split-from") async def add_split_from(location_id: int, data: LocationSplitFrom, conn: AsyncConnection = Depends(get_conn)): loc = await svc.get(conn, location_id) if not loc: raise HTTPException(404, "Lokasyon bulunamadı") await svc.add_split_from(conn, location_id, data) return {"ok": True} @router.post("/merge") async def merge_locations(data: LocationMerge, conn: AsyncConnection = Depends(get_conn)): target = await svc.get(conn, data.target_id) if not target: raise HTTPException(404, "Hedef lokasyon bulunamadı") await svc.merge(conn, data) return {"ok": True, "merged_into": data.target_id} @router.get("/{location_id}/history") async def location_history(location_id: int, conn: AsyncConnection = Depends(get_conn)): return await svc.history(conn, location_id)