"""Consumer connector registration APIs — Phase 11.9."""
from uuid import UUID

from fastapi import APIRouter, Depends, Query, Response, 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.commands.integrations import IntegrationsCommands
from app.permissions.definitions import (
    CONSUMER_CONNECTORS_CREATE,
    CONSUMER_CONNECTORS_DELETE,
    CONSUMER_CONNECTORS_UPDATE,
    CONSUMER_CONNECTORS_VIEW,
)
from app.queries.integrations import IntegrationsQueries
from app.schemas.integrations import (
    ConsumerConnectorRegistrationCreate,
    ConsumerConnectorRegistrationListResponse,
    ConsumerConnectorRegistrationRead,
    ConsumerConnectorRegistrationUpdate,
)
from app.specifications.integrations import (
    CONNECTOR_REGISTRATION_SORT,
    ConsumerConnectorRegistrationListSpec,
)
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


def _spec(
    workspace_id: UUID | None = None,
    site_id: UUID | None = None,
    status_filter: str | None = Query(None, alias="status"),
    kind: str | None = None,
    q: str | None = Query(None, max_length=100),
    sort_by: str = "created_at",
    sort_dir: str = Query("desc", pattern="^(?i)(asc|desc)$"),
):
    return ConsumerConnectorRegistrationListSpec(
        workspace_id=workspace_id,
        site_id=site_id,
        status=status_filter,
        kind=kind,
        q=q,
        sort_by=sort_by if sort_by in CONNECTOR_REGISTRATION_SORT else "created_at",
        sort_dir=sort_dir,
    )


@router.post("", response_model=ConsumerConnectorRegistrationRead, status_code=201)
async def create(
    body: ConsumerConnectorRegistrationCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(CONSUMER_CONNECTORS_CREATE)),
):
    return await IntegrationsCommands(db).create_consumer_connector_registration(
        tenant_id, body, actor=user
    )


@router.get("", response_model=ConsumerConnectorRegistrationListResponse)
async def list_items(
    tenant_id: UUID = Depends(require_tenant),
    pagination: PaginationParams = Depends(get_pagination),
    spec: ConsumerConnectorRegistrationListSpec = Depends(_spec),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(CONSUMER_CONNECTORS_VIEW)),
):
    items, total = await IntegrationsQueries(db).list_consumer_connector_registrations(
        tenant_id, offset=pagination.offset, limit=pagination.page_size, spec=spec
    )
    return ConsumerConnectorRegistrationListResponse(
        items=items, total=total, page=pagination.page, page_size=pagination.page_size
    )


@router.get("/{entity_id}", response_model=ConsumerConnectorRegistrationRead)
async def get(
    entity_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(CONSUMER_CONNECTORS_VIEW)),
):
    return await IntegrationsQueries(db).get_consumer_connector_registration(tenant_id, entity_id)


@router.patch("/{entity_id}", response_model=ConsumerConnectorRegistrationRead)
async def update(
    entity_id: UUID,
    body: ConsumerConnectorRegistrationUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(CONSUMER_CONNECTORS_UPDATE)),
):
    return await IntegrationsCommands(db).update_consumer_connector_registration(
        tenant_id, entity_id, body, actor=user
    )


@router.delete("/{entity_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete(
    entity_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(CONSUMER_CONNECTORS_DELETE)),
):
    await IntegrationsCommands(db).delete_consumer_connector_registration(
        tenant_id, entity_id, actor=user
    )
    return Response(status_code=204)
