//! `robots.txt` generator.

/// Render a `robots.txt` body.
///
/// `disallow_paths` is applied to user-agent `*`. `sitemap_url` is appended as
/// a `Sitemap:` line when provided.
pub fn render_robots_txt(disallow_paths: &[&str], sitemap_url: Option<&str>) -> String {
    let mut out = String::new();
    out.push_str("User-agent: *\n");
    if disallow_paths.is_empty() {
        out.push_str("Allow: /\n");
    } else {
        for p in disallow_paths {
            out.push_str(&format!("Disallow: {p}\n"));
        }
    }
    if let Some(url) = sitemap_url {
        out.push('\n');
        out.push_str(&format!("Sitemap: {url}\n"));
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn allows_all_when_disallow_empty() {
        let body = render_robots_txt(&[], None);
        assert_eq!(body, "User-agent: *\nAllow: /\n");
    }

    #[test]
    fn lists_disallow_paths() {
        let body = render_robots_txt(&["/admin", "/api/htmx"], None);
        assert!(body.contains("Disallow: /admin\n"));
        assert!(body.contains("Disallow: /api/htmx\n"));
        assert!(!body.contains("Allow: /\n"));
    }

    #[test]
    fn appends_sitemap_url() {
        let body = render_robots_txt(&[], Some("https://example.com/sitemap.xml"));
        assert!(body.ends_with("Sitemap: https://example.com/sitemap.xml\n"));
    }
}
