"""Site theme binding APIs — Phase 11.3 (versioned bindings)."""
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.themes import ThemeLayoutCommands
from app.permissions.definitions import THEMES_CREATE, THEMES_DELETE, THEMES_VIEW
from app.queries.themes import ThemeLayoutQueries
from app.schemas.themes import (
    SiteThemeBindingCreate,
    SiteThemeBindingListResponse,
    SiteThemeBindingRead,
)
from app.specifications.themes import (
    SITE_THEME_BINDING_SORT_FIELDS,
    SiteThemeBindingListSpec,
)
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


def _list_spec(
    site_id: UUID | None = Query(default=None),
    theme_id: UUID | None = Query(default=None),
    workspace_id: UUID | None = Query(default=None),
    is_active: bool | None = Query(default=None),
    sort_by: str = Query(default="created_at"),
    sort_dir: str = Query(default="desc", pattern="^(?i)(asc|desc)$"),
) -> SiteThemeBindingListSpec:
    if sort_by not in SITE_THEME_BINDING_SORT_FIELDS:
        sort_by = "created_at"
    return SiteThemeBindingListSpec(
        site_id=site_id,
        theme_id=theme_id,
        workspace_id=workspace_id,
        is_active=is_active,
        sort_by=sort_by,
        sort_dir=sort_dir.lower(),
    )


@router.post(
    "",
    response_model=SiteThemeBindingRead,
    status_code=status.HTTP_201_CREATED,
)
async def assign_site_theme(
    body: SiteThemeBindingCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(THEMES_CREATE)),
):
    return await ThemeLayoutCommands(db).assign_site_theme(tenant_id, body, actor=user)


@router.get("", response_model=SiteThemeBindingListResponse)
async def list_site_theme_bindings(
    tenant_id: UUID = Depends(require_tenant),
    pagination: PaginationParams = Depends(get_pagination),
    spec: SiteThemeBindingListSpec = Depends(_list_spec),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(THEMES_VIEW)),
):
    items, total = await ThemeLayoutQueries(db).list_site_theme_bindings(
        tenant_id, offset=pagination.offset, limit=pagination.page_size, spec=spec
    )
    return SiteThemeBindingListResponse(
        items=items, total=total, page=pagination.page, page_size=pagination.page_size
    )


@router.get("/{binding_id}", response_model=SiteThemeBindingRead)
async def get_site_theme_binding(
    binding_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(THEMES_VIEW)),
):
    return await ThemeLayoutQueries(db).get_site_theme_binding(tenant_id, binding_id)


@router.post("/{binding_id}/unassign", response_model=SiteThemeBindingRead)
async def unassign_site_theme(
    binding_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(THEMES_DELETE)),
):
    return await ThemeLayoutCommands(db).unassign_site_theme(
        tenant_id, binding_id, actor=user
    )
