"""Delivery configuration 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 (
    CONFIGURATIONS_CREATE,
    CONFIGURATIONS_DELETE,
    CONFIGURATIONS_UPDATE,
    CONFIGURATIONS_VIEW,
)
from app.schemas.foundation import (
    HealthcareConfigurationCreate,
    HealthcareConfigurationRead,
    HealthcareConfigurationUpdate,
)
from app.services.foundation import HealthcareConfigurationService
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


@router.post("", response_model=HealthcareConfigurationRead, status_code=status.HTTP_201_CREATED)
async def create_configuration(
    body: HealthcareConfigurationCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(CONFIGURATIONS_CREATE)),
):
    return await HealthcareConfigurationService(db).create(tenant_id, body, actor=user)


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


@router.get("/{configuration_id}", response_model=HealthcareConfigurationRead)
async def get_configuration(
    configuration_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(CONFIGURATIONS_VIEW)),
):
    return await HealthcareConfigurationService(db).get(tenant_id, configuration_id)


@router.patch("/{configuration_id}", response_model=HealthcareConfigurationRead)
async def update_configuration(
    configuration_id: UUID,
    body: HealthcareConfigurationUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(CONFIGURATIONS_UPDATE)),
):
    return await HealthcareConfigurationService(db).update(
        tenant_id, configuration_id, body, actor=user
    )


@router.post("/{configuration_id}/delete", response_model=HealthcareConfigurationRead)
async def soft_delete_configuration(
    configuration_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(CONFIGURATIONS_DELETE)),
):
    return await HealthcareConfigurationService(db).soft_delete(
        tenant_id, configuration_id, actor=user
    )
