"""Shift 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 ShiftStatus
from app.permissions.definitions import (
    SHIFTS_ASSIGNMENTS_MANAGE,
    SHIFTS_ASSIGNMENTS_VIEW,
    SHIFTS_CREATE,
    SHIFTS_DELETE,
    SHIFTS_UPDATE,
    SHIFTS_VIEW,
)
from app.queries.availability import AvailabilityQueries
from app.schemas.availability import (
    ShiftAssignmentCreate,
    ShiftAssignmentRead,
    ShiftAssignmentUpdate,
    ShiftCreate,
    ShiftListResponse,
    ShiftRead,
    ShiftUpdate,
)
from app.specifications.availability import ShiftListSpec
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


def _list_spec(
    status_filter: ShiftStatus | None = Query(default=None, alias="status"),
    organization_id: UUID | None = Query(default=None),
    hub_id: UUID | None = Query(default=None),
    q: str | None = Query(default=None, max_length=100),
    sort_by: str = Query(default="starts_at"),
    sort_dir: str = Query(default="desc", pattern="^(?i)(asc|desc)$"),
) -> ShiftListSpec:
    return ShiftListSpec(
        status=status_filter,
        organization_id=organization_id,
        hub_id=hub_id,
        q=q,
        sort_by=sort_by,
        sort_dir=sort_dir.lower(),
    )


@router.post("", response_model=ShiftRead, status_code=status.HTTP_201_CREATED)
async def create_shift(
    body: ShiftCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(SHIFTS_CREATE)),
):
    return await AvailabilityCommands(db).create_shift(tenant_id, body, actor=user)


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


@router.get("/{shift_id}", response_model=ShiftRead)
async def get_shift(
    shift_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(SHIFTS_VIEW)),
):
    return await AvailabilityQueries(db).get_shift(tenant_id, shift_id)


@router.patch("/{shift_id}", response_model=ShiftRead)
async def update_shift(
    shift_id: UUID,
    body: ShiftUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(SHIFTS_UPDATE)),
):
    return await AvailabilityCommands(db).update_shift(
        tenant_id, shift_id, body, actor=user
    )


@router.post("/{shift_id}/delete", response_model=ShiftRead)
async def delete_shift(
    shift_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(SHIFTS_DELETE)),
):
    return await AvailabilityCommands(db).delete_shift(tenant_id, shift_id, actor=user)


@router.post(
    "/{shift_id}/assignments",
    response_model=ShiftAssignmentRead,
    status_code=status.HTTP_201_CREATED,
)
async def assign_shift(
    shift_id: UUID,
    body: ShiftAssignmentCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(SHIFTS_ASSIGNMENTS_MANAGE)),
):
    return await AvailabilityCommands(db).assign_shift(
        tenant_id, shift_id, body, actor=user
    )


@router.get("/{shift_id}/assignments", response_model=list[ShiftAssignmentRead])
async def list_shift_assignments(
    shift_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(SHIFTS_ASSIGNMENTS_VIEW)),
):
    return await AvailabilityQueries(db).list_shift_assignments(tenant_id, shift_id)


@router.patch(
    "/{shift_id}/assignments/{assignment_id}",
    response_model=ShiftAssignmentRead,
)
async def update_shift_assignment(
    shift_id: UUID,
    assignment_id: UUID,
    body: ShiftAssignmentUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(SHIFTS_ASSIGNMENTS_MANAGE)),
):
    return await AvailabilityCommands(db).update_shift_assignment(
        tenant_id, shift_id, assignment_id, body, actor=user
    )
