const path = require('path');

exports.createPages = async ({graphql, actions, reporter}) => {
    const {createPage} = actions;

    createPage({
        path: '/',
        component: path.resolve(`src/pages/HomePage/HomePage.jsx`),
        context: {
            pagePath: '/',
        },
    });

    createPage({
        path: '/insights/',
        component: path.resolve(`src/pages/List/List.jsx`),
        context: {
            pagePath: '/insights/',
        },
    });

    const result = await graphql(`
    {
      allDataJson {
        nodes {
          name
          images
          tags
          description
          sources
          socialMedia {
            Twitter {
              Social_Media_Influence
              Tweet_Bookmarks
              Tweet_Bookmarks_Relative_to_Average
              Tweet_Likes
              Tweet_Likes_Relative_to_Average
              Tweet_Quotes
              Tweet_Quotes_Relative_to_Average
              Tweet_Reposts
              Tweet_Reposts_Relative_to_Average
              Tweet_Views
              Tweet_Views_Relative_to_Average
              found
            }
            Instagram {
              Post_Comments
              Post_Comments_Relative_to_Average
              Post_Likes
              Post_Likes_Relative_to_Average
              Social_Media_Influence
              found
            }
          }
        }
      }
    }
  `);

    if (result.errors) {
        reporter.panicOnBuild(`Error while running GraphQL query.`);
        return;
    }

    const productPostTemplate = path.resolve(
        `src/templates/ProductPage/ProductPage.jsx`
    );
    result.data.allDataJson.nodes.forEach((node) => {
        const path = `/insights/${node.name.replaceAll(' ', '-').toLowerCase()}`;
        createPage({
            path,
            component: productPostTemplate,
            context: {
                pagePath: path,
                data: node,
                images: node.images,
            },
        });
    });
};
