"""Appointment page APIs — Phase 11.6."""
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.forms import FormsCommands
from app.permissions.definitions import (
    APPOINTMENTS_CREATE,
    APPOINTMENTS_DELETE,
    APPOINTMENTS_UPDATE,
    APPOINTMENTS_VIEW,
)
from app.queries.forms import FormsQueries
from app.schemas.forms import (
    ExperienceAppointmentPageCreate,
    ExperienceAppointmentPageListResponse,
    ExperienceAppointmentPageRead,
    ExperienceAppointmentPageUpdate,
)
from app.specifications.forms import (
    APPOINTMENT_PAGE_SORT_FIELDS,
    AppointmentPageListSpec,
)
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()
_STATUSES = {"draft", "active", "archived"}


def _list_spec(
    workspace_id: UUID | None = Query(default=None),
    site_id: UUID | None = Query(default=None),
    page_id: UUID | None = Query(default=None),
    status_filter: str | None = Query(default=None, alias="status"),
    q: str | None = Query(default=None, max_length=100),
    sort_by: str = Query(default="created_at"),
    sort_dir: str = Query(default="desc", pattern="^(?i)(asc|desc)$"),
) -> AppointmentPageListSpec:
    if sort_by not in APPOINTMENT_PAGE_SORT_FIELDS:
        sort_by = "created_at"
    return AppointmentPageListSpec(
        workspace_id=workspace_id,
        site_id=site_id,
        page_id=page_id,
        status=status_filter if status_filter in _STATUSES else None,
        q=q,
        sort_by=sort_by,
        sort_dir=sort_dir.lower(),
    )


@router.post(
    "",
    response_model=ExperienceAppointmentPageRead,
    status_code=status.HTTP_201_CREATED,
)
async def create_appointment_page(
    body: ExperienceAppointmentPageCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(APPOINTMENTS_CREATE)),
):
    return await FormsCommands(db).create_appointment_page(tenant_id, body, actor=user)


@router.get("", response_model=ExperienceAppointmentPageListResponse)
async def list_appointment_pages(
    tenant_id: UUID = Depends(require_tenant),
    pagination: PaginationParams = Depends(get_pagination),
    spec: AppointmentPageListSpec = Depends(_list_spec),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(APPOINTMENTS_VIEW)),
):
    items, total = await FormsQueries(db).list_appointment_pages(
        tenant_id, offset=pagination.offset, limit=pagination.page_size, spec=spec
    )
    return ExperienceAppointmentPageListResponse(
        items=items, total=total, page=pagination.page, page_size=pagination.page_size
    )


@router.get("/{page_id}", response_model=ExperienceAppointmentPageRead)
async def get_appointment_page(
    page_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(APPOINTMENTS_VIEW)),
):
    return await FormsQueries(db).get_appointment_page(tenant_id, page_id)


@router.patch("/{page_id}", response_model=ExperienceAppointmentPageRead)
async def update_appointment_page(
    page_id: UUID,
    body: ExperienceAppointmentPageUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(APPOINTMENTS_UPDATE)),
):
    return await FormsCommands(db).update_appointment_page(
        tenant_id, page_id, body, actor=user
    )


@router.delete("/{page_id}", response_model=ExperienceAppointmentPageRead)
async def delete_appointment_page(
    page_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(APPOINTMENTS_DELETE)),
):
    return await FormsCommands(db).soft_delete_appointment_page(
        tenant_id, page_id, actor=user
    )
