//! `pic queues ls | show` — read-only queue inspection (G2).
//!
//! Wraps the read-only `/api/v1/admin/apps/{id}/queues*` surface (no
//! purge/requeue — that is v1.2). Gated on `AppLogRead` server-side.

use anyhow::Result;

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

pub async fn ls(app: &str, mode: OutputMode) -> Result<()> {
    let creds = config::resolve()?;
    let client = Client::from_creds(&creds)?;
    let queues = client.queues_list(app).await?;
    let mut table = Table::new(["queue", "total", "pending", "claimed"]);
    for q in queues {
        table.row([
            q.queue_name,
            q.total.to_string(),
            q.pending.to_string(),
            q.claimed.to_string(),
        ]);
    }
    table.print(mode);
    Ok(())
}

pub async fn show(app: &str, queue_name: &str, mode: OutputMode) -> Result<()> {
    let creds = config::resolve()?;
    let client = Client::from_creds(&creds)?;
    let q = client.queue_get(app, queue_name).await?;
    let mut block = KvBlock::new();
    block
        .field("queue", q.queue_name)
        .field("total", q.total.to_string())
        .field("pending", q.pending.to_string())
        .field("claimed", q.claimed.to_string());
    match q.consumer {
        Some(c) => {
            block
                .field("consumer_script", c.script_name)
                .field("consumer_script_id", c.script_id.to_string())
                .field("consumer_trigger_id", c.trigger_id)
                .field(
                    "visibility_timeout_secs",
                    c.visibility_timeout_secs.to_string(),
                )
                .field(
                    "last_fired_at",
                    c.last_fired_at
                        .map(|t| t.to_rfc3339())
                        .unwrap_or_else(|| "-".to_string()),
                );
        }
        None => {
            block.field("consumer", "(none registered)");
        }
    }
    block.print(mode);
    Ok(())
}
