"""Platform administrator read-only listings."""

from __future__ import annotations

from fastapi import APIRouter, Depends, Request
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from aif_platform.server.api.deps import require_platform_admin
from aif_platform.server.api.health import upstream_health_snapshot
from aif_platform.server.db.connection import get_db
from aif_platform.server.models.persistence import PlatformOrganization, PlatformUser
from aif_platform.server.schemas import AdminOrgRow, AdminUserRow

router = APIRouter(prefix="/admin", tags=["admin"])


@router.get("/infra-health")
async def admin_infra_health(
    request: Request,
    _admin: PlatformUser = Depends(require_platform_admin),
) -> dict[str, str]:
    """Upstream reachability for platform operators (same snapshot as public /health)."""
    return await upstream_health_snapshot(request)


@router.get("/users", response_model=list[AdminUserRow])
async def admin_list_users(
    _admin: PlatformUser = Depends(require_platform_admin),
    db: AsyncSession = Depends(get_db),
):
    rows = (await db.execute(select(PlatformUser).order_by(PlatformUser.created_at.asc()))).scalars().all()
    return [
        AdminUserRow(
            id=u.id,
            email=u.email,
            is_active=u.is_active,
            is_platform_admin=u.is_platform_admin,
            created_at=u.created_at,
        )
        for u in rows
    ]


@router.get("/organizations", response_model=list[AdminOrgRow])
async def admin_list_orgs(
    _admin: PlatformUser = Depends(require_platform_admin),
    db: AsyncSession = Depends(get_db),
):
    rows = (
        await db.execute(select(PlatformOrganization).order_by(PlatformOrganization.created_at.asc()))
    ).scalars().all()
    return [AdminOrgRow(id=o.id, name=o.name, created_at=o.created_at) for o in rows]
