'use strict';
require('dotenv').config();
/*
Hey, welcome to the changeset config! This file has been generated
for you with the default configs we use, and some comments around
what options mean, so that it's easy to customise your workflow.

You should update this as you need to craft your workflow.

Config provided by a CI command takes precedence over the contents of this file.

If a config option isn't present here, we will fall back to the defaults.
*/

const changesetOptions = {
  // If true, we will automatically commit the changeset when the command is run
  commit: false,
};

// This function takes information about a changeset to generate an entry for it in your
// changelog. We provide the full changeset object as well as the version.
// It may be a good idea to replace the commit hash with a link to the commit.

/* the default shape is:
- [patch] ABCDEFG:

  A summary message you wrote, indented
*/

function makeQuery(commitShas) {
  return `
    query {
      ${commitShas.map((commitSha, i) => {
        return `a${i}: search(
          type: ISSUE
          query: "sha:${commitSha}+repo:JedWatson/react-select"
          first: 1
        ) {
          edges {
            node {
              ... on PullRequest {
                number
                author {
                  login
                }
              }
            }
          }
        }}`;
      })}
  `;
}

const fetch = require('node-fetch');
const DataLoader = require('dataloader');

const GHDataLoader = new DataLoader(async commitShas => {
  if (!process.env.GITHUB_TOKEN) {
    throw new Error(
      'Please create a GitHub personal access token at https://github.com/settings/tokens/new and add it to a .env file in the root of the repository'
    );
  }
  let data = await fetch(
    `https://api.github.com/graphql?access_token=${process.env.GITHUB_TOKEN}`,
    {
      method: 'POST',
      body: JSON.stringify({ query: makeQuery(commitShas) }),
    }
  ).then(x => x.json());

  // this is mainly for the case where there's an authentication problem
  if (!data.data || !data.data.search || !data.data.search.edges) {
    throw new Error(
      'An error occurred when fetching data from GitHub\n' +
        JSON.stringify(data)
    );
  }
  return data.data.search.edges.map(edge => {
    if (
      edge.node &&
      typeof edge.node.number === 'number' &&
      edge.node.author &&
      typeof node.author.login === 'string'
    ) {
      return { username: edge.node.author.login, number: edge.node.number };
    }
    return null;
  });
});

async function fetchGHData(commitShas) {}

const getReleaseLine = async (changeset, versionType) => {
  const indentedSummary = changeset.summary
    .split('\n')
    .map(l => `  ${l}`.trimRight())
    .join('\n');
  let data = await GHDataLoader.load(changeset.commit);
  if (data !== null) {
    let { number, username } = data;
    return `- [${versionType}] ${
      changeset.commit
    } [#${number}](https://github.com/JedWatson/react-select/pulls/${number}) Thanks [@${username}](https://github.com/${username}):\n\n${indentedSummary}`;
  }
  return `- [${versionType}] ${changeset.commit}:\n\n${indentedSummary}`;
};

// This function takes information about what dependencies we are updating in the package.
// It provides an array of related changesets, as well as the dependencies updated.

/*
- Updated dependencies: [ABCDEFG]:
- Updated dependencies: [HIJKLMN]:
  - dependencyA@1.0.1
  - dependencyb@1.2.0
*/
const getDependencyReleaseLine = async (changesets, dependenciesUpdated) => {
  if (dependenciesUpdated.length === 0) return '';

  const changesetLinks = changesets.map(
    changeset => `- Updated dependencies [${changeset.commit}]:`
  );

  const updatedDepenenciesList = dependenciesUpdated.map(
    dependency => `  - ${dependency.name}@${dependency.version}`
  );

  return [...changesetLinks, ...updatedDepenenciesList].join('\n');
};

const versionOptions = {
  // If true, we will automatically commit the version updating when the command is run
  commit: false,
  // Adds a skipCI flag to the commit - only valid if `commit` is also true.
  skipCI: false,
  // Do not modify the `changelog.md` files for packages that are updated
  noChangelog: false,
  // A function that returns a string. It takes in options about a change. This allows you to customise your changelog entries
  getReleaseLine,
  // A function that returns a string. It takes in options about when a pacakge is updated because
  getDependencyReleaseLine,
};

const publishOptions = {
  // This sets whether unpublished packages are public by default. We err on the side of caution here.
  public: true,
};

module.exports = {
  versionOptions,
  changesetOptions,
  publishOptions,
};

@@ -993,21 +993,41 @@
 mmitShas
-.map(
+%0A        .map(%0A          
 (commitS
@@ -1035,18 +1035,16 @@
 a, i) =%3E
- %7B
 %0A       
@@ -1044,22 +1044,19 @@
         
-return
+   
  %60a$%7Bi%7D:
@@ -1398,20 +1398,40 @@
    %7D
-%7D%60;
+%60
 %0A      
+  )%0A        .join('%5Cn')
 %7D
-)
 %7D%0A  
@@ -2112,56 +2112,8 @@
 data
- %7C%7C !data.data.search %7C%7C !data.data.search.edges
 ) %7B%0A
@@ -2247,39 +2247,48 @@
 urn 
-data.data.search.edges
+Object.values(data.data)
 .map(
+(%7B 
 edge
+s %7D)
  =%3E 
@@ -2304,24 +2304,46 @@
 (%0A      edge
+s%5B0%5D &&%0A      edges%5B0%5D
 .node &&%0A   
@@ -2352,24 +2352,28 @@
  typeof edge
+s%5B0%5D
 .node.number
@@ -2395,24 +2395,28 @@
 &%0A      edge
+s%5B0%5D
 .node.author
@@ -2432,16 +2432,25 @@
  typeof 
+edges%5B0%5D.
 node.aut
@@ -2494,16 +2494,24 @@
 return %7B
+%0A       
  usernam
@@ -2513,24 +2513,28 @@
 ername: edge
+s%5B0%5D
 .node.author
@@ -2540,16 +2540,24 @@
 r.login,
+%0A       
  number:
@@ -2561,16 +2561,20 @@
 er: edge
+s%5B0%5D
 .node.nu
@@ -2577,16 +2577,23 @@
 e.number
+,%0A     
  %7D;%0A    

Fix some bugs in the GH data fetching