mod post;

cfg_if::cfg_if! {
    if #[cfg(feature = "ssr")] {
        use std::collections::HashMap;
        use std::sync::Arc;

        pub struct Data {
            pub posts: Vec<Arc<Post>>,
            pub posts_by_slug: HashMap<String, Arc<Post>>,
            pub posts_by_tag: HashMap<String, Vec<Arc<Post>>>,
            pub tags: Vec<String>,
        }

        impl Data {
            #[allow(dead_code)] // Use in main.rs
            pub fn new() -> anyhow::Result<Self> {
                let mut posts = crate::app::utils::data_src::get_all::<Post>("posts")?;
                posts.sort_by(|post, post2| post2.metadata.date.cmp(&post.metadata.date));

                let posts = posts.into_iter()
                    .map(Arc::new)
                    .collect::<Vec<_>>();


                let mut tags : Vec<String> = Vec::new();
                let mut posts_by_slug : HashMap<String, Arc<Post>> = HashMap::new();
                let mut posts_by_tag : HashMap<String, Vec<Arc<Post>>> = HashMap::new();

                for post in &posts {
                    posts_by_slug.insert(post.metadata.slug.clone(), post.clone());

                    for tag in &post.metadata.tags {
                        let tag_lower = tag.to_lowercase();

                        if let None = tags.iter().find(|t| t.to_lowercase().eq(&tag_lower)) {
                            tags.push(tag.clone());
                        }

                        let posts = posts_by_tag.entry(tag_lower).or_default();
                        posts.push(post.clone());
                    }
                }

                log::info!("Loaded {} posts", posts.len());
                log::info!("Found {} tags in global", tags.len());
                log::info!("Found {} tags from posts", posts_by_tag.len());

                Ok(Self {
                    posts,
                    posts_by_slug,
                    posts_by_tag,
                    tags
                })
            }
        }


    }
}

pub use post::{Post, PostMetadata};
