"""Page component placement APIs — Phase 11.2 composition shells."""
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.components import ComponentCommands
from app.permissions.definitions import (
    COMPONENTS_CREATE,
    COMPONENTS_DELETE,
    COMPONENTS_UPDATE,
    COMPONENTS_VIEW,
)
from app.queries.components import ComponentQueries
from app.schemas.components import (
    PageComponentPlacementCreate,
    PageComponentPlacementListResponse,
    PageComponentPlacementRead,
    PageComponentPlacementUpdate,
)
from app.specifications.components import PLACEMENT_SORT_FIELDS, PlacementListSpec
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


def _list_spec(
    page_id: UUID | None = Query(default=None),
    site_id: UUID | None = Query(default=None),
    component_id: UUID | None = Query(default=None),
    q: str | None = Query(default=None, max_length=100),
    sort_by: str = Query(default="sort_order"),
    sort_dir: str = Query(default="asc", pattern="^(?i)(asc|desc)$"),
) -> PlacementListSpec:
    if sort_by not in PLACEMENT_SORT_FIELDS:
        sort_by = "sort_order"
    return PlacementListSpec(
        page_id=page_id,
        site_id=site_id,
        component_id=component_id,
        q=q,
        sort_by=sort_by,
        sort_dir=sort_dir.lower(),
    )


@router.post(
    "",
    response_model=PageComponentPlacementRead,
    status_code=status.HTTP_201_CREATED,
)
async def create_placement(
    body: PageComponentPlacementCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(COMPONENTS_CREATE)),
):
    return await ComponentCommands(db).create_placement(tenant_id, body, actor=user)


@router.get("", response_model=PageComponentPlacementListResponse)
async def list_placements(
    tenant_id: UUID = Depends(require_tenant),
    pagination: PaginationParams = Depends(get_pagination),
    spec: PlacementListSpec = Depends(_list_spec),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(COMPONENTS_VIEW)),
):
    items, total = await ComponentQueries(db).list_placements(
        tenant_id,
        offset=pagination.offset,
        limit=pagination.page_size,
        spec=spec,
    )
    return PageComponentPlacementListResponse(
        items=items,
        total=total,
        page=pagination.page,
        page_size=pagination.page_size,
    )


@router.get("/{placement_id}", response_model=PageComponentPlacementRead)
async def get_placement(
    placement_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(COMPONENTS_VIEW)),
):
    return await ComponentQueries(db).get_placement(tenant_id, placement_id)


@router.patch("/{placement_id}", response_model=PageComponentPlacementRead)
async def update_placement(
    placement_id: UUID,
    body: PageComponentPlacementUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(COMPONENTS_UPDATE)),
):
    return await ComponentCommands(db).update_placement(
        tenant_id, placement_id, body, actor=user
    )


@router.post("/{placement_id}/delete", response_model=PageComponentPlacementRead)
async def soft_delete_placement(
    placement_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(COMPONENTS_DELETE)),
):
    return await ComponentCommands(db).soft_delete_placement(
        tenant_id, placement_id, actor=user
    )
