//! `GET /api/device-group/accessible` — paginated list of device groups the
//! caller is a member of (admin sees all). The Flutter client at
//! flutter/lib/models/group_model.dart:103 silently tolerates errors here, so
//! we keep the behavior tight: empty list when no groups exist, never panic.

use crate::api::error::ApiError;
use crate::api::middleware::AuthedUser;
use crate::api::pagination::{Page, PageQuery};
use crate::api::state::AppState;
use axum::extract::{Extension, Query};
use axum::Json;
use serde::Serialize;
use std::sync::Arc;

#[derive(Debug, Serialize)]
pub struct DeviceGroupOut {
    pub name: String,
}

pub async fn accessible(
    Extension(state): Extension<Arc<AppState>>,
    user: AuthedUser,
    Query(q): Query<PageQuery>,
) -> Result<Json<Page<DeviceGroupOut>>, ApiError> {
    let (total, rows) = state
        .db
        .groups_list_for_user(user.user_id, user.is_admin, q.offset(), q.limit())
        .await
        .map_err(|e| ApiError::Internal(e.to_string()))?;
    Ok(Json(Page {
        total,
        data: rows
            .into_iter()
            .map(|g| DeviceGroupOut { name: g.name })
            .collect(),
    }))
}
