//! `rok routes:list` — scan `src/routes/` and print a formatted route table.

use std::path::Path;

use crate::route_parser::scan_routes_dir;

pub fn run() -> anyhow::Result<()> {
    let routes_dir = Path::new("src/routes");
    if !routes_dir.exists() {
        anyhow::bail!("src/routes/ not found. Run `rok routes:list` from the project root.");
    }

    let all_routes = scan_routes_dir()?;

    if all_routes.is_empty() {
        println!("  (no routes found in src/routes/)");
        return Ok(());
    }

    let mut max_method = 6;
    let mut max_path = 4;
    let mut max_name = 4;
    let mut max_ctrl = 10;
    let mut max_mw = 10;

    for r in &all_routes {
        max_method = max_method.max(r.method.len());
        max_path = max_path.max(r.path.len());
        max_name = max_name.max(r.name.as_deref().unwrap_or("").len());
        max_ctrl = max_ctrl.max(r.controller.as_deref().unwrap_or("").len());
        let mw = r.middleware.join(", ");
        max_mw = max_mw.max(mw.len());
    }

    let method_w = max_method + 2;
    let path_w = max_path + 2;
    let name_w = max_name.max(4) + 2;
    let ctrl_w = max_ctrl.max(10) + 2;
    let mw_w = max_mw.max(10) + 2;

    println!(
        "{:<mw$} {:<pw$} {:<nw$} {:<cw$} {:<mwid$} HANDLER",
        "METHOD", "PATH", "NAME", "CONTROLLER", "MIDDLEWARE",
        mw = method_w, pw = path_w, nw = name_w, cw = ctrl_w, mwid = mw_w
    );
    println!("{}", "-".repeat(method_w + path_w + name_w + ctrl_w + mw_w + 80));

    for r in &all_routes {
        let mw = r.middleware.join(", ");
        println!(
            "{:<mw$} {:<pw$} {:<nw$} {:<cw$} {:<mwid$} {}",
            r.method,
            r.path,
            r.name.as_deref().unwrap_or(""),
            r.controller.as_deref().unwrap_or(""),
            mw,
            r.handler,
            mw = method_w, pw = path_w, nw = name_w, cw = ctrl_w, mwid = mw_w
        );
    }

    Ok(())
}
