/*
 * 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 { getMockProjectsFromWorkingGroup } from './mock-data';
import { buildMockPaginationLinkHeader } from '../mock-helpers';

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

const handlers = [
    rest.get(`${apiUrl}/projects`, (req, res, ctx) => {
      const workingGroup = req.url.searchParams.get('working_group');
      const page = +req.url.searchParams.get('page') || 1;
      const pageSize = 3;

      if (!workingGroup) return res(ctx.status(400));

      const projects = getMockProjectsFromWorkingGroup(workingGroup).api;

      // Pagination mock
      const hasMoreProjectAdopters = page * pageSize < projects.length;
      const linkHeader = buildMockPaginationLinkHeader(req, hasMoreProjectAdopters);

      const startIndex = (page - 1) * pageSize;
      const remainingDataCount = projects.length - startIndex;
      const endIndex = startIndex + Math.min(pageSize, remainingDataCount);

      const result = projects.length === 0 ? [] : projects.slice(startIndex, endIndex);

      return res(
          ctx.status(200),
          ctx.set({
            Link: linkHeader,
          }),
          ctx.json(result)
      );
  })
];

export default handlers;
