"""Healthcare clinic 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 (
    CLINICS_CREATE,
    CLINICS_DELETE,
    CLINICS_UPDATE,
    CLINICS_VIEW,
)
from app.schemas.foundation import ClinicCreate, ClinicRead, ClinicUpdate
from app.services.foundation import ClinicService
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


@router.post("", response_model=ClinicRead, status_code=status.HTTP_201_CREATED)
async def create_clinic(
    body: ClinicCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(CLINICS_CREATE)),
):
    return await ClinicService(db).create(tenant_id, body, actor=user)


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


@router.get("/{clinic_id}", response_model=ClinicRead)
async def get_clinic(
    clinic_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(CLINICS_VIEW)),
):
    return await ClinicService(db).get(tenant_id, clinic_id)


@router.patch("/{clinic_id}", response_model=ClinicRead)
async def update_clinic(
    clinic_id: UUID,
    body: ClinicUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(CLINICS_UPDATE)),
):
    return await ClinicService(db).update(tenant_id, clinic_id, body, actor=user)


@router.post("/{clinic_id}/delete", response_model=ClinicRead)
async def soft_delete_clinic(
    clinic_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(CLINICS_DELETE)),
):
    return await ClinicService(db).soft_delete(tenant_id, clinic_id, actor=user)
