"""Booking engine registration APIs — Phase 14.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 (
    BOOKING_ENGINES_CREATE,
    BOOKING_ENGINES_DELETE,
    BOOKING_ENGINES_UPDATE,
    BOOKING_ENGINES_VIEW,
)
from app.schemas.foundation import (
    BookingEngineRegistrationCreate,
    BookingEngineRegistrationRead,
    BookingEngineRegistrationUpdate,
)
from app.services.foundation import BookingEngineRegistrationService
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


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


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


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


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


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