"""Experience organization APIs — Phase 11.0."""
from __future__ import annotations

from uuid import UUID

from fastapi import APIRouter, Depends, 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.permissions.definitions import (
    WORKSPACES_CREATE,
    WORKSPACES_DELETE,
    WORKSPACES_UPDATE,
    WORKSPACES_VIEW,
)
from app.schemas.foundation import (
    ExperienceWorkspaceCreate,
    ExperienceWorkspaceRead,
    ExperienceWorkspaceUpdate,
)
from app.services.foundation import ExperienceWorkspaceService
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


@router.post("", response_model=ExperienceWorkspaceRead, status_code=status.HTTP_201_CREATED)
async def create_workspace(
    body: ExperienceWorkspaceCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(WORKSPACES_CREATE)),
):
    return await ExperienceWorkspaceService(db).create(tenant_id, body, actor=user)


@router.get("", response_model=list[ExperienceWorkspaceRead])
async def list_workspaces(
    tenant_id: UUID = Depends(require_tenant),
    pagination: PaginationParams = Depends(get_pagination),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(WORKSPACES_VIEW)),
):
    return await ExperienceWorkspaceService(db).list(
        tenant_id, offset=pagination.offset, limit=pagination.page_size
    )


@router.get("/{workspace_id}", response_model=ExperienceWorkspaceRead)
async def get_workspace(
    workspace_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(WORKSPACES_VIEW)),
):
    return await ExperienceWorkspaceService(db).get(tenant_id, workspace_id)


@router.patch("/{workspace_id}", response_model=ExperienceWorkspaceRead)
async def update_workspace(
    workspace_id: UUID,
    body: ExperienceWorkspaceUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(WORKSPACES_UPDATE)),
):
    return await ExperienceWorkspaceService(db).update(
        tenant_id, workspace_id, body, actor=user
    )


@router.post("/{workspace_id}/delete", response_model=ExperienceWorkspaceRead)
async def soft_delete_workspace(
    workspace_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(WORKSPACES_DELETE)),
):
    return await ExperienceWorkspaceService(db).soft_delete(
        tenant_id, workspace_id, actor=user
    )
