"""Delivery hub 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 HUBS_CREATE, HUBS_DELETE, HUBS_UPDATE, HUBS_VIEW
from app.schemas.foundation import DeliveryHubCreate, DeliveryHubRead, DeliveryHubUpdate
from app.services.foundation import DeliveryHubService
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


@router.post("", response_model=DeliveryHubRead, status_code=status.HTTP_201_CREATED)
async def create_hub(
    body: DeliveryHubCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(HUBS_CREATE)),
):
    return await DeliveryHubService(db).create(tenant_id, body, actor=user)


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


@router.get("/{hub_id}", response_model=DeliveryHubRead)
async def get_hub(
    hub_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(HUBS_VIEW)),
):
    return await DeliveryHubService(db).get(tenant_id, hub_id)


@router.patch("/{hub_id}", response_model=DeliveryHubRead)
async def update_hub(
    hub_id: UUID,
    body: DeliveryHubUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(HUBS_UPDATE)),
):
    return await DeliveryHubService(db).update(tenant_id, hub_id, body, actor=user)


@router.post("/{hub_id}/delete", response_model=DeliveryHubRead)
async def soft_delete_hub(
    hub_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(HUBS_DELETE)),
):
    return await DeliveryHubService(db).soft_delete(tenant_id, hub_id, actor=user)
