//! `pic docs ls | get --app <slug> | --group <slug>` — read-only inspection of a
//! docs collection. Both owners are supported: `--app` browses an app's own docs
//! collection, `--group` a group's shared-docs collection (§11.6).
//!
//! Read-only by design (matching `pic kv`): docs writes go through
//! `docs::create/update` (or `docs::shared_collection(...).create/update`) in
//! scripts, which emit the change events 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(
    app: Option<&str>,
    group: Option<&str>,
    collection: &str,
    limit: u32,
    mode: OutputMode,
) -> Result<()> {
    let creds = config::resolve()?;
    let client = Client::from_creds(&creds)?;
    let page = match crate::cmds::require_one_owner(app, group)? {
        crate::cmds::OwnerRef::App(a) => client.docs_list(a, collection, limit).await?,
        crate::cmds::OwnerRef::Group(g) => client.group_docs_list(g, 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(
    app: Option<&str>,
    group: Option<&str>,
    collection: &str,
    doc_id: &str,
) -> Result<()> {
    let creds = config::resolve()?;
    let client = Client::from_creds(&creds)?;
    let value = match crate::cmds::require_one_owner(app, group)? {
        crate::cmds::OwnerRef::App(a) => client.docs_get(a, collection, doc_id).await?,
        crate::cmds::OwnerRef::Group(g) => client.group_docs_get(g, 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(())
}
