const path = require(`path`)
const slash = require(`slash`)

exports.createPages = ({ boundActionCreators, graphql }) => {
  const { createPage } = boundActionCreators

  return new Promise((resolve, reject) => {
    const articleTemplate = path.resolve(`src/templates/article.js`)
    // Query for markdown nodes to use in creating pages.
    resolve(
      graphql(
        `
      {
        allMarkdownRemark(
          limit: 1000,
          filter: {frontmatter: {draft: {eq: false}}},
        ) {
          edges {
            node {
              frontmatter {
                title
                slug
              }
            }
          }
        }
      }
    `
      ).then(result => {
        if (result.errors) {
          reject(result.errors)
        }

        // Create pages for each markdown file.
        result.data.allMarkdownRemark.edges.forEach(({ node }) => {
        //   const path = node.frontmatter.path;
          const slug = node.frontmatter.slug;
          createPage({
            path: slug,
            component: articleTemplate,
            // In your blog post template's graphql query, you can use path
            // as a GraphQL variable to query for data from the markdown file.
            context: {
              slug,
            }
          })
        })
      })
    )
  })
}
