"""Core entitlement reference binding APIs — Phase 11.8."""
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.bundles import BundlesCommands
from app.permissions.definitions import BUNDLES_CREATE, BUNDLES_DELETE, BUNDLES_UPDATE, BUNDLES_VIEW
from app.queries.bundles import BundlesQueries
from app.schemas.bundles import LicenseBindingCreate, LicenseBindingListResponse, LicenseBindingRead, LicenseBindingUpdate
from app.specifications.bundles import LICENSE_BINDING_SORT, LicenseBindingListSpec
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()

def _spec(workspace_id: UUID | None = None, status_filter: str | None = Query(None, alias="status"),
          bundle_key: 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 LicenseBindingListSpec(workspace_id=workspace_id, status=status_filter, bundle_key=bundle_key, q=q,
                                  sort_by=sort_by if sort_by in LICENSE_BINDING_SORT else "created_at", sort_dir=sort_dir)

@router.post("", response_model=LicenseBindingRead, status_code=201)
async def create(body: LicenseBindingCreate, tenant_id: UUID = Depends(require_tenant), db: AsyncSession = Depends(get_db),
                 user: CurrentUser = Depends(require_permissions(BUNDLES_CREATE))):
    return await BundlesCommands(db).create_license_binding(tenant_id, body, actor=user)

@router.get("", response_model=LicenseBindingListResponse)
async def list_items(tenant_id: UUID = Depends(require_tenant), pagination: PaginationParams = Depends(get_pagination),
                     spec: LicenseBindingListSpec = Depends(_spec), db: AsyncSession = Depends(get_db),
                     _user: CurrentUser = Depends(require_permissions(BUNDLES_VIEW))):
    items, total = await BundlesQueries(db).list_license_bindings(tenant_id, offset=pagination.offset, limit=pagination.page_size, spec=spec)
    return LicenseBindingListResponse(items=items, total=total, page=pagination.page, page_size=pagination.page_size)

@router.get("/{entity_id}", response_model=LicenseBindingRead)
async def get(entity_id: UUID, tenant_id: UUID = Depends(require_tenant), db: AsyncSession = Depends(get_db),
              _user: CurrentUser = Depends(require_permissions(BUNDLES_VIEW))):
    return await BundlesQueries(db).get_license_binding(tenant_id, entity_id)

@router.patch("/{entity_id}", response_model=LicenseBindingRead)
async def update(entity_id: UUID, body: LicenseBindingUpdate, tenant_id: UUID = Depends(require_tenant),
                 db: AsyncSession = Depends(get_db), user: CurrentUser = Depends(require_permissions(BUNDLES_UPDATE))):
    return await BundlesCommands(db).update_license_binding(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(BUNDLES_DELETE))):
    await BundlesCommands(db).delete_license_binding(tenant_id, entity_id, actor=user)
    return Response(status_code=204)
