/*
 * 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 { rest } from 'msw';
import { mockOrganizations, mockOrganizationsByProject, mockOrganizationsByWorkingGroup } from './mock-data';

const apiUrl = 'https://membership.eclipse.org/api';

const handlers = [
  rest.get(`${apiUrl}/organizations/:id`, (req, res, ctx) => {
    const organizationId = parseInt(req.params.id);
    const organization = mockOrganizations.find(o => o.organization_id === organizationId);

    // If no organizations are found for the project, return a 404.
    if (!organization) {
      return res(
        ctx.status(404),
      );
    }

    return res(
      ctx.status(200),
      ctx.json(organization),
    );
  }),

  rest.get(`${apiUrl}/organizations`, (req, res, ctx) => {
    const url = new URL(req.url);
    const workingGroup = url.searchParams.get('working_group');

    let organizations;
    if (workingGroup) {
      // If a working group is provided, set organizations to the organizations
      // under that working group.
      organizations = mockOrganizationsByWorkingGroup[workingGroup]; 
    } else {
      // By default, set organizations to all organizations.
      organizations = mockOrganizations;
    }

    return res(
      ctx.status(200),
      ctx.json(organizations),
    );
  }),

  rest.get(`${apiUrl}/projects/:project/organizations`, (req, res, ctx) => {
    const project = req.params.project;
    const organizations = mockOrganizationsByProject[project];

    // If no organizations are found for the project, return a 404.
    if (!organizations) {
      return res(
        ctx.status(404),
      );
    }
   
    return res(
      ctx.status(200),
      ctx.json(organizations)
    );
  }),
];

export default handlers;
