"""Capability bundle 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 CapabilityBundleStatus
from app.permissions.definitions import (
    BUNDLES_CREATE,
    BUNDLES_DELETE,
    BUNDLES_UPDATE,
    BUNDLES_VIEW,
)
from app.queries.pricing import PricingQueries
from app.schemas.pricing import (
    BundleCreate,
    BundleListResponse,
    BundleRead,
    BundleUpdate,
)
from app.specifications.pricing import BundleListSpec
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


def _list_spec(
    status_filter: CapabilityBundleStatus | 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)$"),
) -> BundleListSpec:
    return BundleListSpec(
        status=status_filter, q=q, sort_by=sort_by, sort_dir=sort_dir.lower()
    )


@router.post("", response_model=BundleRead, status_code=status.HTTP_201_CREATED)
async def create_bundle(
    body: BundleCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(BUNDLES_CREATE)),
):
    return await PricingCommands(db).create_bundle(tenant_id, body, actor=user)


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


@router.get("/{bundle_id}", response_model=BundleRead)
async def get_bundle(
    bundle_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(BUNDLES_VIEW)),
):
    return await PricingQueries(db).get_bundle(tenant_id, bundle_id)


@router.patch("/{bundle_id}", response_model=BundleRead)
async def update_bundle(
    bundle_id: UUID,
    body: BundleUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(BUNDLES_UPDATE)),
):
    return await PricingCommands(db).update_bundle(
        tenant_id, bundle_id, body, actor=user
    )


@router.post("/{bundle_id}/delete", response_model=BundleRead)
async def delete_bundle(
    bundle_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(BUNDLES_DELETE)),
):
    return await PricingCommands(db).delete_bundle(tenant_id, bundle_id, actor=user)
