"""External provider config APIs — Phase 10.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 (
    EXTERNAL_PROVIDERS_CREATE,
    EXTERNAL_PROVIDERS_DELETE,
    EXTERNAL_PROVIDERS_UPDATE,
    EXTERNAL_PROVIDERS_VIEW,
)
from app.schemas.foundation import (
    ExternalProviderConfigCreate,
    ExternalProviderConfigRead,
    ExternalProviderConfigUpdate,
)
from app.services.foundation import ExternalProviderConfigService
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


@router.post("", response_model=ExternalProviderConfigRead, status_code=status.HTTP_201_CREATED)
async def create_provider(
    body: ExternalProviderConfigCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(EXTERNAL_PROVIDERS_CREATE)),
):
    return await ExternalProviderConfigService(db).create(tenant_id, body, actor=user)


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


@router.get("/{provider_id}", response_model=ExternalProviderConfigRead)
async def get_provider(
    provider_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(EXTERNAL_PROVIDERS_VIEW)),
):
    return await ExternalProviderConfigService(db).get(tenant_id, provider_id)


@router.patch("/{provider_id}", response_model=ExternalProviderConfigRead)
async def update_provider(
    provider_id: UUID,
    body: ExternalProviderConfigUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(EXTERNAL_PROVIDERS_UPDATE)),
):
    return await ExternalProviderConfigService(db).update(
        tenant_id, provider_id, body, actor=user
    )


@router.post("/{provider_id}/delete", response_model=ExternalProviderConfigRead)
async def soft_delete_provider(
    provider_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(EXTERNAL_PROVIDERS_DELETE)),
):
    return await ExternalProviderConfigService(db).soft_delete(
        tenant_id, provider_id, actor=user
    )
