"""Routing engine registration APIs — Phase 10.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.api.permissions import require_permissions
from app.permissions.definitions import (
    ROUTING_ENGINES_CREATE,
    ROUTING_ENGINES_DELETE,
    ROUTING_ENGINES_UPDATE,
    ROUTING_ENGINES_VIEW,
)
from app.schemas.foundation import (
    RoutingEngineRegistrationCreate,
    RoutingEngineRegistrationRead,
    RoutingEngineRegistrationUpdate,
)
from app.services.foundation import RoutingEngineRegistrationService
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


@router.post("", response_model=RoutingEngineRegistrationRead, status_code=status.HTTP_201_CREATED)
async def create_engine(
    body: RoutingEngineRegistrationCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(ROUTING_ENGINES_CREATE)),
):
    return await RoutingEngineRegistrationService(db).create(tenant_id, body, actor=user)


@router.get("", response_model=list[RoutingEngineRegistrationRead])
async def list_engines(
    tenant_id: UUID = Depends(require_tenant),
    pagination: PaginationParams = Depends(get_pagination),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(ROUTING_ENGINES_VIEW)),
):
    return await RoutingEngineRegistrationService(db).list(
        tenant_id, offset=pagination.offset, limit=pagination.page_size
    )


@router.get("/{engine_id}", response_model=RoutingEngineRegistrationRead)
async def get_engine(
    engine_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(ROUTING_ENGINES_VIEW)),
):
    return await RoutingEngineRegistrationService(db).get(tenant_id, engine_id)


@router.patch("/{engine_id}", response_model=RoutingEngineRegistrationRead)
async def update_engine(
    engine_id: UUID,
    body: RoutingEngineRegistrationUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(ROUTING_ENGINES_UPDATE)),
):
    return await RoutingEngineRegistrationService(db).update(
        tenant_id, engine_id, body, actor=user
    )


@router.post("/{engine_id}/delete", response_model=RoutingEngineRegistrationRead)
async def soft_delete_engine(
    engine_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(ROUTING_ENGINES_DELETE)),
):
    return await RoutingEngineRegistrationService(db).soft_delete(
        tenant_id, engine_id, actor=user
    )
