"""Healthcare doctor 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 (
    DOCTORS_CREATE,
    DOCTORS_DELETE,
    DOCTORS_UPDATE,
    DOCTORS_VIEW,
)
from app.schemas.profiles import DoctorCreate, DoctorRead, DoctorUpdate
from app.services.profiles import DoctorService
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


@router.post("", response_model=DoctorRead, status_code=status.HTTP_201_CREATED)
async def create_doctor(
    body: DoctorCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(DOCTORS_CREATE)),
):
    return await DoctorService(db).create(tenant_id, body, actor=user)


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


@router.get("/{doctor_id}", response_model=DoctorRead)
async def get_doctor(
    doctor_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(DOCTORS_VIEW)),
):
    return await DoctorService(db).get(tenant_id, doctor_id)


@router.patch("/{doctor_id}", response_model=DoctorRead)
async def update_doctor(
    doctor_id: UUID,
    body: DoctorUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(DOCTORS_UPDATE)),
):
    return await DoctorService(db).update(tenant_id, doctor_id, body, actor=user)


@router.post("/{doctor_id}/delete", response_model=DoctorRead)
async def soft_delete_doctor(
    doctor_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(DOCTORS_DELETE)),
):
    return await DoctorService(db).soft_delete(tenant_id, doctor_id, actor=user)
