"""Customer tracking token APIs — Phase 10.7."""
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.tracking import TrackingCommands
from app.models.types import CustomerTrackingTokenStatus
from app.permissions.definitions import (
    CUSTOMER_TRACKING_CREATE,
    CUSTOMER_TRACKING_REVOKE,
    CUSTOMER_TRACKING_VIEW,
)
from app.queries.tracking import TrackingQueries
from app.schemas.tracking import (
    CustomerTrackingTokenCreate,
    CustomerTrackingTokenListResponse,
    CustomerTrackingTokenRead,
)
from app.specifications.tracking import CustomerTrackingTokenListSpec
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


def _list_spec(
    status_filter: CustomerTrackingTokenStatus | None = Query(default=None, alias="status"),
    dispatch_job_id: UUID | None = Query(default=None),
    sort_by: str = Query(default="created_at"),
    sort_dir: str = Query(default="desc", pattern="^(?i)(asc|desc)$"),
) -> CustomerTrackingTokenListSpec:
    return CustomerTrackingTokenListSpec(
        status=status_filter,
        dispatch_job_id=dispatch_job_id,
        sort_by=sort_by,
        sort_dir=sort_dir.lower(),
    )


@router.post("/tokens", response_model=CustomerTrackingTokenRead, status_code=status.HTTP_201_CREATED)
async def create_token(
    body: CustomerTrackingTokenCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(CUSTOMER_TRACKING_CREATE)),
):
    return await TrackingCommands(db).create_token(tenant_id, body, actor=user)


@router.get("/tokens", response_model=CustomerTrackingTokenListResponse)
async def list_tokens(
    tenant_id: UUID = Depends(require_tenant),
    pagination: PaginationParams = Depends(get_pagination),
    spec: CustomerTrackingTokenListSpec = Depends(_list_spec),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(CUSTOMER_TRACKING_VIEW)),
):
    items, total = await TrackingQueries(db).list_tokens(
        tenant_id, offset=pagination.offset, limit=pagination.page_size, spec=spec
    )
    return CustomerTrackingTokenListResponse(
        items=items, total=total, page=pagination.page, page_size=pagination.page_size
    )


@router.get("/tokens/{token_id}", response_model=CustomerTrackingTokenRead)
async def get_token(
    token_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(CUSTOMER_TRACKING_VIEW)),
):
    return await TrackingQueries(db).get_token(tenant_id, token_id)


@router.post("/tokens/{token_id}/revoke", response_model=CustomerTrackingTokenRead)
async def revoke_token(
    token_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(CUSTOMER_TRACKING_REVOKE)),
):
    return await TrackingCommands(db).revoke_token(tenant_id, token_id, actor=user)
