//! `pic interceptors ls --app|--group` — read-only view of a node's §9.4
//! service interceptors. For an app, the RESOLVED chain view (every marker
//! guarding its writes, nearest-owner-wins — what actually runs); for a group,
//! its own declared markers. Authoring is declarative only (the manifest
//! `[[interceptors]]`).

use anyhow::Result;

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

pub async fn ls(app: Option<&str>, group: Option<&str>, mode: OutputMode) -> Result<()> {
    let (kind, ident) = match crate::cmds::require_one_owner(app, group)? {
        OwnerRef::App(a) => (NodeKind::App, a),
        OwnerRef::Group(g) => (NodeKind::Group, g),
    };
    let creds = config::resolve()?;
    let client = Client::from_creds(&creds)?;
    let items = client.interceptors_list(kind, ident).await?;

    let mut table = Table::new(["service", "op", "phase", "script", "timeout_ms"]);
    for i in &items {
        table.row([
            i.service.clone(),
            i.op.clone(),
            i.phase.clone(),
            i.script.clone(),
            i.timeout_ms
                .map_or_else(|| "-".to_string(), |t| t.to_string()),
        ]);
    }
    table.print(mode);
    Ok(())
}
