/*
 * Copyright 2023 Adobe. All rights reserved.
 * This file is licensed to you under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License. You may obtain a copy
 * of the License at http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
 * OF ANY KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
import { Response } from '@adobe/fetch';

export function addCommonResponseHeadersWrapper(fn) {
  return async (req, context) => {
    const res = await fn(req, context);
    if (!res.headers.has('cache-control')) {
      res.headers.set('cache-control', 'no-store, private, must-revalidate');
    }

    // add CORS headers if origin is present
    const origin = req.headers.get('origin');
    if (origin) {
      // echo the requested origin back to the client. You may like to
      // check this against a whitelist of origins instead of blindly
      // allowing potentially destructive requests from any origin
      res.headers.set('access-control-allow-origin', origin);

      // The Access-Control-Allow-Credentials response header tells browsers whether
      // to expose the response to the frontend JavaScript code when the request's
      // credentials mode (Request.credentials) is include.
      res.headers.set('access-control-allow-credentials', 'true');

      // The Access-Control-Expose-Headers response header allows a server to
      // indicate which response headers should be made available to scripts
      // running in the browser, in response to a cross-origin request.
      res.headers.set('access-control-expose-headers', 'x-error');
    }
    return res;
  };
}

export function optionsHandler() {
  return new Response('', {
    status: 204,
    headers: {
      'access-control-allow-methods': 'GET, HEAD, POST, OPTIONS, DELETE',
      'access-control-allow-headers': 'Authorization, x-auth-token',
      'access-control-max-age': '86400',
    },
  });
}
