""" Device Management API — Register and manage phones/softphones. Row mapping lives in call_persistence; this layer works with the Device domain model only. """ import uuid from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.ext.asyncio import AsyncSession from api.deps import get_gateway from core.gateway import AIPSTNGateway from db.database import get_db from models.device import Device, DeviceCreate, DeviceUpdate from services import call_persistence as store router = APIRouter() @router.post("/", response_model=Device) async def register_device( device: DeviceCreate, gateway: AIPSTNGateway = Depends(get_gateway), db: AsyncSession = Depends(get_db), ): """Register a new device with the gateway.""" dev = Device(id=f"dev_{uuid.uuid4().hex[:8]}", **device.model_dump()) await store.create_device_row(db, dev) gateway.register_device(dev) return dev @router.get("/", response_model=list[Device]) async def list_devices( gateway: AIPSTNGateway = Depends(get_gateway), ): """List all registered devices and their status.""" return list(gateway.devices.values()) @router.get("/{device_id}", response_model=Device) async def get_device( device_id: str, gateway: AIPSTNGateway = Depends(get_gateway), ): """Get a specific device.""" device = gateway.devices.get(device_id) if not device: raise HTTPException(status_code=404, detail=f"Device {device_id} not found") return device @router.put("/{device_id}", response_model=Device) async def update_device( device_id: str, update: DeviceUpdate, gateway: AIPSTNGateway = Depends(get_gateway), db: AsyncSession = Depends(get_db), ): """Update a device.""" device = gateway.devices.get(device_id) if not device: raise HTTPException(status_code=404, detail=f"Device {device_id} not found") update_data = update.model_dump(exclude_unset=True) for key, value in update_data.items(): setattr(device, key, value) await store.update_device_row(db, device_id, update_data) return device @router.delete("/{device_id}") async def unregister_device( device_id: str, gateway: AIPSTNGateway = Depends(get_gateway), db: AsyncSession = Depends(get_db), ): """Unregister a device.""" if device_id not in gateway.devices: raise HTTPException(status_code=404, detail=f"Device {device_id} not found") gateway.unregister_device(device_id) await store.delete_device_row(db, device_id) return {"status": "unregistered", "device_id": device_id}