/*
 * 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 { mockNewsroomResources, mockAds } from './mock-data';

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

const handlers = [
  rest.post(`${apiUrl}/ads`, async (req, res, ctx) => {
    const payload = await req.json();
    const ads = mockAds
      .filter(ad => ad.publish_to.includes(payload.publish_to))
      //.filter(ad => Object.keys(payload.format).includes(ad.format));

    return res(
      ctx.status(200),
      ctx.json(ads)
    );
  }),
  rest.get(`${apiUrl}/resources`, (req, res, ctx) => {
    const publishTo = req.url.searchParams.getAll('parameters[publish_to][]')
    const resourceTypes = req.url.searchParams.getAll('parameters[resource_type][]')
    const pageSize = req.url.searchParams.get('pagesize')

    let data = mockNewsroomResources;
    
    // Filter resources based on publishTo query parameter. 
    if (publishTo.length !== 0) {
      data = data.filter(resource => 
        publishTo.some(p => resource.publish_to.includes(p))
      );
    }
    
    // Filter resources based on resourceTypes query parameter.
    if (resourceTypes.length !== 0) {
      data = data.filter(resource => 
        resourceTypes.some(t => resource.resource_type.includes(t))
      );
    }

    if (pageSize) {
      data = data.slice(0, pageSize);
    }

    const hasMoreResources = false;
    const linkHeaderBase = `<${req.url.href}>; rel=self`;
    const linkHeaderText = hasMoreResources
      ? `${linkHeaderBase}, <${req.url.href}&page=${page + 1}>; rel=next`
      : linkHeaderBase;

    return res(
      ctx.status(200),
      ctx.set({ 'Link': linkHeaderText }),
      ctx.json({ resources: data })
    );
  })
];

export default handlers;
