mod post;

pub use post::{Post, PostMetadata};

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>>>,
        }

        impl Data {
            #[allow(dead_code)] // Use in main.rs
            pub fn new() -> anyhow::Result<Self> {
                let posts = crate::app::utils::data_src::get_all::<Post>("posts")?
                    .into_iter()
                    .map(Arc::new)
                    .collect::<Vec<_>>();

                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 = tag.to_lowercase();
                        let posts = posts_by_tag.entry(tag).or_default();
                        posts.push(post.clone());
                    }
                }

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

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


    }
}