//! `pic docs ls | get --group` — read-only inspection of a group's shared-docs
//! collection (§11.6). Group-only: per-app docs have no admin read route yet
//! (unlike kv/files), so there is no `--app` variant here.
//!
//! Read-only by design (matching `pic kv`): docs writes go through
//! `docs::shared_collection(...).create/update` in scripts, which emit the
//! change events shared triggers depend on; an admin write would bypass that.

use anyhow::Result;

use crate::client::Client;
use crate::config;
use crate::output::{OutputMode, Table};

pub async fn ls(group: &str, collection: &str, limit: u32, mode: OutputMode) -> Result<()> {
    let creds = config::resolve()?;
    let client = Client::from_creds(&creds)?;
    let page = client.group_docs_list(group, collection, limit).await?;
    let mut table = Table::new(["id"]);
    for d in page.docs {
        table.row([d.id]);
    }
    table.print(mode);
    if page.next_cursor.is_some() {
        eprintln!("(more documents available — raise --limit to see them)");
    }
    Ok(())
}

pub async fn get(group: &str, collection: &str, doc_id: &str) -> Result<()> {
    let creds = config::resolve()?;
    let client = Client::from_creds(&creds)?;
    let value = client.group_docs_get(group, collection, doc_id).await?;
    // Emit the document JSON (pretty) so it pipes cleanly into jq.
    let pretty = serde_json::to_string_pretty(&value).unwrap_or_else(|_| value.to_string());
    println!("{pretty}");
    Ok(())
}
