"""Device APIs — Phase 9.0."""
from __future__ import annotations

from uuid import UUID

from fastapi import APIRouter, Depends, status
from sqlalchemy.ext.asyncio import AsyncSession

from app.api.deps import get_db, get_pagination, require_tenant
from app.core.security import get_current_user
from app.schemas.foundation import (
    DeviceCreate,
    DeviceRead,
    DeviceUpdate,
)
from app.services.foundation import DeviceService
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


@router.post("", response_model=DeviceRead, status_code=status.HTTP_201_CREATED)
async def create_item(
    body: DeviceCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(get_current_user),
):
    return await DeviceService(db).create(tenant_id, body, actor=user)


@router.get("", response_model=list[DeviceRead])
async def list_items(
    tenant_id: UUID = Depends(require_tenant),
    pagination: PaginationParams = Depends(get_pagination),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(get_current_user),
):
    return await DeviceService(db).list(tenant_id, offset=pagination.offset, limit=pagination.page_size)


@router.get("/{device_id}", response_model=DeviceRead)
async def get_item(
    device_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(get_current_user),
):
    return await DeviceService(db).get(tenant_id, device_id)


@router.patch("/{device_id}", response_model=DeviceRead)
async def update_item(
    device_id: UUID,
    body: DeviceUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(get_current_user),
):
    return await DeviceService(db).update(tenant_id, device_id, body, actor=user)


@router.post("/{device_id}/delete", response_model=DeviceRead)
async def soft_delete_item(
    device_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(get_current_user),
):
    return await DeviceService(db).soft_delete(tenant_id, device_id, actor=user)


@router.post("/{device_id}/connect", response_model=DeviceRead)
async def connect_device(
    device_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(get_current_user),
):
    return await DeviceService(db).connect(tenant_id, device_id, actor=user)


@router.post("/{device_id}/disconnect", response_model=DeviceRead)
async def disconnect_device(
    device_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(get_current_user),
):
    return await DeviceService(db).disconnect(tenant_id, device_id, actor=user)
