module.exports = (eleventyConfig) => {
    eleventyConfig.addCollection('tags', (collectionApi) => {
        const tags = new Set();
        collectionApi.getFilteredByTag("posts")
            .filter(p => process.env.DEBUG || !p.data.tags.includes("draft"))
            .filter(p => process.env.DEBUG || p.date < new Date())
            .forEach((item) => {
                if (!item.data.tags) return;
                item.data.tags.forEach((tag) => tags.add(tag));
            });
        return [...tags];
    });

    eleventyConfig.addCollection('tagPosts', (collectionApi) => {
        const tagPosts = {};
        collectionApi.getFilteredByTag("posts")
            .filter(p => process.env.DEBUG || !p.data.tags.includes("draft"))
            .filter(p => process.env.DEBUG || p.date < new Date())
            .forEach((item) => {
                if (!item.data.tags) return;
                item.data.tags.forEach((tag) => {
                    if (!(tag in tagPosts)) {
                        tagPosts[tag] = [];
                    }
                    tagPosts[tag] = [item, ...tagPosts[tag]];
                });
            });
        return tagPosts;
    });
}