/*!
 * Copyright (c) 2019, 2022, 2023 Eclipse Foundation, Inc.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v. 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0.
 *
 * Contributors:
 *   Eric Poirier <eric.poirier@eclipse-foundation.org>
 *   Olivier Goulet <olivier.goulet@eclipse-foundation.org>
 *
 * SPDX-License-Identifier: EPL-2.0
 */

import parse from 'parse-link-header';
import { validateURL } from '../utils/utils';
import 'isomorphic-fetch';

const apiBasePath = 'https://api.eclipse.org/adopters';

const getProjectsWithAdopters = async (workingGroup, projects = [], nextUrl = undefined) => {
  let url;

  if (!nextUrl) {
    url = `${apiBasePath}/projects`;
    url += workingGroup ? `?working_group=${workingGroup}` : '';
  } else {
    url = nextUrl;
  }

  if (!validateURL(url)) return projects; 

  const response = await fetch(url);
  const data = await response.json();
  projects = projects.concat(data);
  
  const linkHeader = parse(response.headers.get('Link'));
  if (linkHeader === undefined || linkHeader.next === undefined) return projects; 

  return getProjectsWithAdopters(workingGroup, projects, linkHeader.next.url);
};

export default getProjectsWithAdopters;
