"""PWA manifest 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 PWA_CREATE, PWA_UPDATE, PWA_VIEW
from app.queries.publishing import PublishingQueries
from app.schemas.publishing import PwaManifestListResponse, PwaManifestRead, PwaManifestUpdate, PwaManifestUpsert
from app.specifications.publishing import PWA_SORT, PwaManifestListSpec
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, 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 PwaManifestListSpec(workspace_id=workspace_id, site_id=site_id, status=status_filter, q=q,
        sort_by=sort_by if sort_by in PWA_SORT else "created_at", sort_dir=sort_dir)
@router.post("", response_model=PwaManifestRead, status_code=status.HTTP_201_CREATED)
async def upsert(body: PwaManifestUpsert, tenant_id: UUID = Depends(require_tenant), db: AsyncSession = Depends(get_db), user: CurrentUser = Depends(require_permissions(PWA_CREATE))):
    return await PublishingCommands(db).upsert_pwa(tenant_id, body, actor=user)
@router.get("", response_model=PwaManifestListResponse)
async def list_items(tenant_id: UUID = Depends(require_tenant), pagination: PaginationParams = Depends(get_pagination), spec: PwaManifestListSpec = Depends(_list_spec), db: AsyncSession = Depends(get_db), _user: CurrentUser = Depends(require_permissions(PWA_VIEW))):
    items, total = await PublishingQueries(db).list_pwa(tenant_id, offset=pagination.offset, limit=pagination.page_size, spec=spec)
    return PwaManifestListResponse(items=items, total=total, page=pagination.page, page_size=pagination.page_size)
@router.get("/{entity_id}", response_model=PwaManifestRead)
async def get(entity_id: UUID, tenant_id: UUID = Depends(require_tenant), db: AsyncSession = Depends(get_db), _user: CurrentUser = Depends(require_permissions(PWA_VIEW))):
    return await PublishingQueries(db).get_pwa(tenant_id, entity_id)
@router.patch("/{entity_id}", response_model=PwaManifestRead)
async def update(entity_id: UUID, body: PwaManifestUpdate, tenant_id: UUID = Depends(require_tenant), db: AsyncSession = Depends(get_db), user: CurrentUser = Depends(require_permissions(PWA_UPDATE))):
    return await PublishingCommands(db).update_pwa(tenant_id, entity_id, body, actor=user)
