"""Healthcare department APIs — Phase 13.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 (
    DEPARTMENTS_CREATE,
    DEPARTMENTS_DELETE,
    DEPARTMENTS_UPDATE,
    DEPARTMENTS_VIEW,
)
from app.schemas.foundation import DepartmentCreate, DepartmentRead, DepartmentUpdate
from app.services.foundation import DepartmentService
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


@router.post("", response_model=DepartmentRead, status_code=status.HTTP_201_CREATED)
async def create_department(
    body: DepartmentCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(DEPARTMENTS_CREATE)),
):
    return await DepartmentService(db).create(tenant_id, body, actor=user)


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


@router.get("/{department_id}", response_model=DepartmentRead)
async def get_department(
    department_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(DEPARTMENTS_VIEW)),
):
    return await DepartmentService(db).get(tenant_id, department_id)


@router.patch("/{department_id}", response_model=DepartmentRead)
async def update_department(
    department_id: UUID,
    body: DepartmentUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(DEPARTMENTS_UPDATE)),
):
    return await DepartmentService(db).update(tenant_id, department_id, body, actor=user)


@router.post("/{department_id}/delete", response_model=DepartmentRead)
async def soft_delete_department(
    department_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(DEPARTMENTS_DELETE)),
):
    return await DepartmentService(db).soft_delete(tenant_id, department_id, actor=user)
