//! Twitter Card meta tags (`<meta name="twitter:*">`).

use html_escape::encode_double_quoted_attribute;

use crate::types::PageSeo;

/// Render all Twitter Card tags derived from `seo.twitter`.
pub fn render_twitter_tags(seo: &PageSeo) -> String {
    let tw = &seo.twitter;
    let mut out = String::new();
    out.push_str(&meta_name("twitter:card", tw.card.as_str()));
    out.push_str(&meta_name("twitter:title", &tw.title));
    if let Some(d) = &tw.description {
        out.push_str(&meta_name("twitter:description", d));
    }
    if let Some(img) = &tw.image {
        out.push_str(&meta_name("twitter:image", img));
    }
    if let Some(alt) = &tw.image_alt {
        out.push_str(&meta_name("twitter:image:alt", alt));
    }
    if let Some(site) = &tw.site {
        out.push_str(&meta_name("twitter:site", site));
    }
    if let Some(creator) = &tw.creator {
        out.push_str(&meta_name("twitter:creator", creator));
    }
    out
}

fn meta_name(name: &str, content: &str) -> String {
    format!(
        r#"<meta name="{}" content="{}">"#,
        name,
        encode_double_quoted_attribute(content)
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{PageSeo, TwitterCardKind};

    #[test]
    fn defaults_to_summary_large_image() {
        let seo = PageSeo::new("Home", "https://example.com/", "en");
        let html = render_twitter_tags(&seo);
        assert!(html.contains(r#"name="twitter:card" content="summary_large_image""#));
        assert!(html.contains(r#"name="twitter:title" content="Home""#));
    }

    #[test]
    fn switches_card_kind() {
        let mut seo = PageSeo::new("Home", "https://example.com/", "en");
        seo.twitter.card = TwitterCardKind::Summary;
        let html = render_twitter_tags(&seo);
        assert!(html.contains(r#"name="twitter:card" content="summary""#));
    }

    #[test]
    fn renders_creator_and_site() {
        let mut seo = PageSeo::new("Home", "https://example.com/", "en");
        seo.twitter.site = Some("@example".into());
        seo.twitter.creator = Some("@author".into());
        let html = render_twitter_tags(&seo);
        assert!(html.contains(r#"name="twitter:site" content="@example""#));
        assert!(html.contains(r#"name="twitter:creator" content="@author""#));
    }
}
