"""APIهای ServiceRegistry."""
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
from app.core.security import require_authenticated, require_platform_admin
from app.schemas.service_registry import (
    ServiceCreate,
    ServiceRead,
    ServiceStatusUpdate,
)
from app.services.service_registry_service import ServiceRegistryService
from shared.pagination import Page, PaginationParams

router = APIRouter(prefix="/services", tags=["service-registry"])


@router.post("", response_model=ServiceRead, status_code=status.HTTP_201_CREATED)
async def create_service(
    payload: ServiceCreate,
    db: AsyncSession = Depends(get_db),
    _user=Depends(require_platform_admin),
) -> ServiceRead:
    service = await ServiceRegistryService(db).create(payload)
    return ServiceRead.model_validate(service)


@router.get("", response_model=Page[ServiceRead])
async def list_services(
    pagination: PaginationParams = Depends(get_pagination),
    db: AsyncSession = Depends(get_db),
    _user=Depends(require_authenticated),
) -> Page[ServiceRead]:
    items, total = await ServiceRegistryService(db).list(
        offset=pagination.offset, limit=pagination.limit
    )
    return Page.create(
        [ServiceRead.model_validate(s) for s in items], total, pagination
    )


@router.patch("/{service_id}/status", response_model=ServiceRead)
async def update_service_status(
    service_id: UUID,
    payload: ServiceStatusUpdate,
    db: AsyncSession = Depends(get_db),
    _user=Depends(require_platform_admin),
) -> ServiceRead:
    service = await ServiceRegistryService(db).update_status(service_id, payload.status)
    return ServiceRead.model_validate(service)
