"""Healthcare patient 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 (
    PATIENTS_CREATE,
    PATIENTS_DELETE,
    PATIENTS_UPDATE,
    PATIENTS_VIEW,
)
from app.schemas.profiles import PatientCreate, PatientRead, PatientUpdate
from app.services.profiles import PatientService
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


@router.post("", response_model=PatientRead, status_code=status.HTTP_201_CREATED)
async def create_patient(
    body: PatientCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(PATIENTS_CREATE)),
):
    return await PatientService(db).create(tenant_id, body, actor=user)


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


@router.get("/{patient_id}", response_model=PatientRead)
async def get_patient(
    patient_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(PATIENTS_VIEW)),
):
    return await PatientService(db).get(tenant_id, patient_id)


@router.patch("/{patient_id}", response_model=PatientRead)
async def update_patient(
    patient_id: UUID,
    body: PatientUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(PATIENTS_UPDATE)),
):
    return await PatientService(db).update(tenant_id, patient_id, body, actor=user)


@router.post("/{patient_id}/delete", response_model=PatientRead)
async def soft_delete_patient(
    patient_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(PATIENTS_DELETE)),
):
    return await PatientService(db).soft_delete(tenant_id, patient_id, actor=user)
