/*
 * Copyright (c) 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:
 *   Olivier Goulet <olivier.goulet@eclipse-foundation.org>
 *
 * SPDX-License-Identifier: EPL-2.0
 */

import 'isomorphic-fetch';
import { getOrganizationById } from './eclipsefdn.membership';
import { transformSnakeToCamel } from './utils';

const apiBasePath = 'https://projects.eclipse.org/api/interest-groups';

export const getInterestGroup = async ({ interestGroupNodeId, interestGroupId }) => {
  try {
    let url;
    if (interestGroupId) {
      url = `${apiBasePath}?project_id=foundation-internal.ig.${interestGroupId}`;
    } else if (interestGroupNodeId) {
      url = `${apiBasePath}/${interestGroupNodeId}`;
    } else {
      throw new TypeError('No interestGroupId or interestGroupNodeId provided to getInterestGroup');
    }

    const response = await fetch(url);
    if (!response.ok) throw new Error(
        interestGroupId 
          ? `Could not fetch interest group for id "${interestGroupId}". Ensure that you are using the same value as project_short_id from the API`
          : `Could not fetch interest group for node id "${interestGroupNodeId}"`
      );
    
    // Request without node id will return an array of one element
    const data = interestGroupNodeId 
      ? await response.json()
      : (await response.json())[0];
    const interestGroup = transformSnakeToCamel(data);

    return [interestGroup, null];
  } catch (error) {
    return [null, error];
  }
}

export const getInterestGroups = async () => {
  try {
    const response = await fetch(`${apiBasePath}`);
    if (!response.ok) throw new Error(`Could not fetch interest groups`);
    
    const data = await response.json();
    const interestGroups = transformSnakeToCamel(data);

    return [interestGroups, null];
  } catch (error) {
    return [null, error];
  }
}

export const getInterestGroupParticipatingOrganizations = async (options) => {
  try {
    const [interestGroup, error] = await getInterestGroup(options);
    if (error) throw new Error(error);

    /*
      Create an array from a set of organizations from participants and leads. The set guarantees that the 
      organizations have no duplicates.
    */
    const participatingOrganizationIds = [
      ...new Set([...interestGroup.participants, ...interestGroup.leads].map(p => Number.parseInt(p.organization.id)))
    ];

    /*
      Get all participating organizations from organization id. Filter out the ones which had errors 
      for whatever reason.
    */
    const participatingOrganizations = (
      await Promise.all(
        participatingOrganizationIds.map(async participantId => {
          const [participant, participantError] = await getOrganizationById(Number.parseInt(participantId));

          if (participantError) {
            console.error(`Could not fetch participant organization from id ${participantId}`);
          }

          return participant;
        })
      )
    ).filter(participant => participant !== null);

    return [participatingOrganizations, null];
  } catch (error) {
    console.error(error);
    return [null, error];
  }
};
