"""Working zone APIs — Phase 10.3."""
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.availability import AvailabilityCommands
from app.models.types import WorkingZoneStatus
from app.permissions.definitions import (
    WORKING_ZONES_CREATE,
    WORKING_ZONES_DELETE,
    WORKING_ZONES_UPDATE,
    WORKING_ZONES_VIEW,
)
from app.queries.availability import AvailabilityQueries
from app.schemas.availability import (
    WorkingZoneCreate,
    WorkingZoneListResponse,
    WorkingZoneRead,
    WorkingZoneUpdate,
)
from app.specifications.availability import WorkingZoneListSpec
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


def _list_spec(
    status_filter: WorkingZoneStatus | None = Query(default=None, alias="status"),
    organization_id: UUID | None = Query(default=None),
    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)$"),
) -> WorkingZoneListSpec:
    return WorkingZoneListSpec(
        status=status_filter,
        organization_id=organization_id,
        q=q,
        sort_by=sort_by,
        sort_dir=sort_dir.lower(),
    )


@router.post("", response_model=WorkingZoneRead, status_code=status.HTTP_201_CREATED)
async def create_zone(
    body: WorkingZoneCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(WORKING_ZONES_CREATE)),
):
    return await AvailabilityCommands(db).create_zone(tenant_id, body, actor=user)


@router.get("", response_model=WorkingZoneListResponse)
async def list_zones(
    tenant_id: UUID = Depends(require_tenant),
    pagination: PaginationParams = Depends(get_pagination),
    spec: WorkingZoneListSpec = Depends(_list_spec),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(WORKING_ZONES_VIEW)),
):
    items, total = await AvailabilityQueries(db).list_zones(
        tenant_id, offset=pagination.offset, limit=pagination.page_size, spec=spec
    )
    return WorkingZoneListResponse(
        items=items, total=total, page=pagination.page, page_size=pagination.page_size
    )


@router.get("/{zone_id}", response_model=WorkingZoneRead)
async def get_zone(
    zone_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(WORKING_ZONES_VIEW)),
):
    return await AvailabilityQueries(db).get_zone(tenant_id, zone_id)


@router.patch("/{zone_id}", response_model=WorkingZoneRead)
async def update_zone(
    zone_id: UUID,
    body: WorkingZoneUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(WORKING_ZONES_UPDATE)),
):
    return await AvailabilityCommands(db).update_zone(
        tenant_id, zone_id, body, actor=user
    )


@router.post("/{zone_id}/delete", response_model=WorkingZoneRead)
async def delete_zone(
    zone_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(WORKING_ZONES_DELETE)),
):
    return await AvailabilityCommands(db).delete_zone(tenant_id, zone_id, actor=user)
