const path = require(`path`);
const { postsPerPage } = require(`./src/utils/siteConfig`);
const { paginate } = require(`gatsby-awesome-pagination`);

/**
 * Here is the place where Gatsby creates the URLs for all the
 * posts, tags, pages and authors that we fetched from the Ghost site.
 */
exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions;

  const result = await graphql(`
    {
      allGhostPost(sort: { published_at: ASC }) {
        edges {
          node {
            slug
            tags{
              slug
            }
          }
        }
      }
      allGhostTag(sort: { name: ASC }) {
        edges {
          node {
            slug
            url
            postCount
          }
        }
      }
      allGhostAuthor(sort: { name: ASC }) {
        edges {
          node {
            slug
            url
            postCount
          }
        }
      }
      allGhostPage(sort: { published_at: ASC }) {
        edges {
          node {
            slug
            url
          }
        }
      }
    }
  `);

  // Check for any errors
  if (result.errors) {
    throw new Error(result.errors);
  }

  // Extract query results
  const tags = result.data.allGhostTag.edges;
  const authors = result.data.allGhostAuthor.edges;
  const pages = result.data.allGhostPage.edges;
  const posts = result.data.allGhostPost.edges;

  // Load templates
  const indexTemplate = path.resolve(`./src/templates/index.js`);
  const tagsTemplate = path.resolve(`./src/templates/tag.js`);
  const authorTemplate = path.resolve(`./src/templates/author.js`);
  const pageTemplate = path.resolve(`./src/templates/page.js`);
  const postTemplate = path.resolve(`./src/templates/post.js`);
  const blogsTemplate = path.resolve(`./src/templates/blogs.js`);

  paginate({
    createPage,
    items: posts,
    itemsPerPage: postsPerPage,
    component: blogsTemplate,
    pathPrefix: "posts",
    context: {
      pathPrefix: "posts",
      // slug: node.slug,
    },
  });

  // Create tag pages
  tags.forEach(({ node }) => {
    const totalPosts = node.postCount !== null ? node.postCount : 0;

    // This part here defines, that our tag pages will use
    // a `/tag/:slug/` permalink.
    const url = `tag/${node.slug}`;

    const items = Array.from({ length: totalPosts });

    // Create pagination
    paginate({
      createPage,
      items: items,
      itemsPerPage: postsPerPage,
      component: tagsTemplate,
      pathPrefix: url,
      context: {
        pathPrefix: url,
        slug: node.slug,
      },
    });
  });

  // Create author pages
  authors.forEach(({ node }) => {
    const totalPosts = node.postCount !== null ? node.postCount : 0;

    // This part here defines, that our author pages will use
    // a `/author/:slug/` permalink.
    const url = `author/${node.slug}`;

    const items = Array.from({ length: totalPosts });

    // Create pagination
    paginate({
      createPage,
      items: items,
      itemsPerPage: postsPerPage,
      component: authorTemplate,
      pathPrefix: url,
      context: {
        pathPrefix: url,
        slug: node.slug,
      },
    });
  });

  // Create pages
  pages.forEach(({ node }) => {
    // This part here defines, that our pages will use
    // a `/:slug/` permalink.
    node.url = `/${node.slug}/`;

    createPage({
      path: node.url,
      component: pageTemplate,
      context: {
        // Data passed to context is available
        // in page queries as GraphQL variables.
        slug: node.slug,
        tags: node.tags,
      },
    });
  });

  // Create post pages
  posts.forEach(({ node }) => {
    // This part here defines, that our posts will use
    // a `/:slug/` permalink.
    node.url = `/${node.slug}/`;

    createPage({
      path: node.url,
      component: postTemplate,
      context: {
        // Data passed to context is available
        // in page queries as GraphQL variables.
        slug: node.slug,
      },
    });
  });

  // Create pagination
  paginate({
    createPage,
    items: posts,
    itemsPerPage: postsPerPage,
    component: indexTemplate,
    pathPrefix: ({ pageNumber }) => {
      if (pageNumber === 0) {
        return `/`;
      } else {
        return `/page`;
      }
    },
  });
};

exports.onCreateWebpackConfig = ({ stage, actions }) => {
  actions.setWebpackConfig({
    resolve: {
      fallback: { url: require.resolve("url/") },
    },
  });
};
