export default async function getStarsForUser(username: string) {
  const userResponse = await request(`/users/${username}`);
  if (!userResponse || !userResponse.public_repos) {
    throw new Error(userResponse ? userResponse.message : 'User not found.');
  }

  const pages = Math.ceil(userResponse.public_repos / 100);
  let repos = [];
  const fetchReposPromises = [];

  for (let i = 1; i <= pages; i++) {
    fetchReposPromises.push(request(`/users/${username}/repos?per_page=100&page=${i}`));
  }

  const reposResponses = await Promise.all(fetchReposPromises);
  repos = reposResponses.flat();

  return starSum(repos);
}

async function request(url) {
  const headers= {
    'User-Agent': 'GitHub StarCounter',
    // Authorization: `Basic ${Buffer.from(auth).toString('base64')}`
  };

  const response = await fetch(`https://api.github.com${url}`, { headers });
  return response.json()
}

async function starSum(repos) {
  return repos.reduce((acc, curr) => acc + curr.stargazers_count, 0);
}
