"""Routing engine registration APIs — Phase 11.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 (
    RENDER_ENGINES_CREATE,
    RENDER_ENGINES_DELETE,
    RENDER_ENGINES_UPDATE,
    RENDER_ENGINES_VIEW,
)
from app.schemas.foundation import (
    RenderEngineRegistrationCreate,
    RenderEngineRegistrationRead,
    RenderEngineRegistrationUpdate,
)
from app.services.foundation import RenderEngineRegistrationService
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


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


@router.get("", response_model=list[RenderEngineRegistrationRead])
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(RENDER_ENGINES_VIEW)),
):
    return await RenderEngineRegistrationService(db).list(
        tenant_id, offset=pagination.offset, limit=pagination.page_size
    )


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


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


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