"""Domain edge binding APIs — Phase 11.7."""
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.publishing import PublishingCommands
from app.permissions.definitions import PUBLISHING_CREATE, PUBLISHING_UPDATE, PUBLISHING_VIEW
from app.queries.publishing import PublishingQueries
from app.schemas.publishing import DomainEdgeBindingCreate, DomainEdgeBindingListResponse, DomainEdgeBindingRead, DomainEdgeBindingUpdate
from app.specifications.publishing import DomainEdgeBindingListSpec, EDGE_SORT
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()

def _list_spec(workspace_id: UUID | None = None, site_id: UUID | None = None, site_domain_id: UUID | None = None,
               status_filter: str | None = Query(default=None, alias="status"), q: str | None = Query(default=None, max_length=100),
               sort_by: str = "created_at", sort_dir: str = Query(default="desc", pattern="^(?i)(asc|desc)$")):
    return DomainEdgeBindingListSpec(workspace_id=workspace_id, site_id=site_id, site_domain_id=site_domain_id,
        status=status_filter, q=q, sort_by=sort_by if sort_by in EDGE_SORT else "created_at", sort_dir=sort_dir)

@router.post("", response_model=DomainEdgeBindingRead, status_code=status.HTTP_201_CREATED)
async def create(body: DomainEdgeBindingCreate, tenant_id: UUID = Depends(require_tenant), db: AsyncSession = Depends(get_db),
                 user: CurrentUser = Depends(require_permissions(PUBLISHING_CREATE))):
    return await PublishingCommands(db).create_domain_edge_binding(tenant_id, body, actor=user)

@router.get("", response_model=DomainEdgeBindingListResponse)
async def list_items(tenant_id: UUID = Depends(require_tenant), pagination: PaginationParams = Depends(get_pagination),
                     spec: DomainEdgeBindingListSpec = Depends(_list_spec), db: AsyncSession = Depends(get_db),
                     _user: CurrentUser = Depends(require_permissions(PUBLISHING_VIEW))):
    items, total = await PublishingQueries(db).list_domain_edge_bindings(tenant_id, offset=pagination.offset, limit=pagination.page_size, spec=spec)
    return DomainEdgeBindingListResponse(items=items, total=total, page=pagination.page, page_size=pagination.page_size)

@router.get("/{entity_id}", response_model=DomainEdgeBindingRead)
async def get(entity_id: UUID, tenant_id: UUID = Depends(require_tenant), db: AsyncSession = Depends(get_db),
              _user: CurrentUser = Depends(require_permissions(PUBLISHING_VIEW))):
    return await PublishingQueries(db).get_domain_edge_binding(tenant_id, entity_id)

@router.patch("/{entity_id}", response_model=DomainEdgeBindingRead)
async def update(entity_id: UUID, body: DomainEdgeBindingUpdate, tenant_id: UUID = Depends(require_tenant),
                 db: AsyncSession = Depends(get_db), user: CurrentUser = Depends(require_permissions(PUBLISHING_UPDATE))):
    return await PublishingCommands(db).update_domain_edge_binding(tenant_id, entity_id, body, actor=user)
