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

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

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

    const projects = industryCollaboration
      ? mockProjects.filter((project) => project.industry_collaborations.some(collaboration => collaboration.id === industryCollaboration))
      : mockProjects;

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

    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)
    );
  }),
  rest.get(`${apiUrl}/proposals`, (req, res, ctx) => {
    const industryCollaboration = req.url.searchParams.get('industry_collaboration');
    const page = +req.url.searchParams.get('page') || 1;
    const pageSize = 3;

    const proposals = industryCollaboration
      ? mockProposals.filter((proposal) => proposal.industry_collaboration.id === industryCollaboration)
      : mockProposals;

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

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

    const result = proposals.length === 0 ? [] : {
      result: proposals.slice(startIndex, endIndex)
    }

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

export default handlers;
