"""Capability APIs — Phase 10.4."""
from __future__ import annotations

from uuid import UUID

from fastapi import APIRouter, Depends, Query, 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.pricing import PricingCommands
from app.models.types import CapabilityStatus
from app.permissions.definitions import (
    CAPABILITIES_CREATE,
    CAPABILITIES_DELETE,
    CAPABILITIES_UPDATE,
    CAPABILITIES_VIEW,
)
from app.queries.pricing import PricingQueries
from app.schemas.pricing import (
    CapabilityCreate,
    CapabilityListResponse,
    CapabilityRead,
    CapabilityUpdate,
)
from app.specifications.pricing import CapabilityListSpec
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


def _list_spec(
    status_filter: CapabilityStatus | None = Query(default=None, alias="status"),
    q: str | None = Query(default=None, max_length=100),
    sort_by: str = Query(default="created_at"),
    sort_dir: str = Query(default="desc", pattern="^(?i)(asc|desc)$"),
) -> CapabilityListSpec:
    return CapabilityListSpec(
        status=status_filter, q=q, sort_by=sort_by, sort_dir=sort_dir.lower()
    )


@router.post("", response_model=CapabilityRead, status_code=status.HTTP_201_CREATED)
async def create_capability(
    body: CapabilityCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(CAPABILITIES_CREATE)),
):
    return await PricingCommands(db).create_capability(tenant_id, body, actor=user)


@router.get("", response_model=CapabilityListResponse)
async def list_capabilities(
    tenant_id: UUID = Depends(require_tenant),
    pagination: PaginationParams = Depends(get_pagination),
    spec: CapabilityListSpec = Depends(_list_spec),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(CAPABILITIES_VIEW)),
):
    items, total = await PricingQueries(db).list_capabilities(
        tenant_id, offset=pagination.offset, limit=pagination.page_size, spec=spec
    )
    return CapabilityListResponse(
        items=items, total=total, page=pagination.page, page_size=pagination.page_size
    )


@router.get("/{cap_id}", response_model=CapabilityRead)
async def get_capability(
    cap_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(CAPABILITIES_VIEW)),
):
    return await PricingQueries(db).get_capability(tenant_id, cap_id)


@router.patch("/{cap_id}", response_model=CapabilityRead)
async def update_capability(
    cap_id: UUID,
    body: CapabilityUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(CAPABILITIES_UPDATE)),
):
    return await PricingCommands(db).update_capability(
        tenant_id, cap_id, body, actor=user
    )


@router.post("/{cap_id}/delete", response_model=CapabilityRead)
async def delete_capability(
    cap_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(CAPABILITIES_DELETE)),
):
    return await PricingCommands(db).delete_capability(tenant_id, cap_id, actor=user)
