/*
 * Copyright 2019 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 wrap from '@adobe/helix-shared-wrap';
import { logger } from '@adobe/helix-universal-logger';
import { wrap as status } from '@adobe/helix-status';
import { Response } from '@adobe/fetch';
import fetch from 'node-fetch';
import bodyData from '@adobe/helix-shared-body-data';
import { getAllForms } from './FormsImporter.js';
import { addCommonResponseHeadersWrapper } from './support/cors.js';
import { FormType } from './support/type.js';
import claim from './cache/claim.js';
import claimAF from './cache/claim_af2.js';

const urlPattern = /^(https?|http):\/\/[^\s/$.?#].[^\s]*$/;
const defaultUserAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36';

function isURL(url) {
  return url && urlPattern.test(url);
}

async function getContent(url, userAgent = defaultUserAgent) {
  let result;
  let headers;
  try {
    if (userAgent) {
      headers = {
        'User-Agent': userAgent,
      };
    }
    const response = await fetch(url, {
      headers,
    });
    if (response.ok) {
      result = await response.text();
    }
  } catch (e) {
    console.log('Error-', e);
  }
  return result;
}

const cachedUrls = [
  'https://www.stewart.com/en/contact-us/submit-a-claim.html',
  'https://www.stewart.com/en/contact-us/submit-a-claim',
  'https://preprod.stewart.com/en/contact-us/submit-a-claim',
];

function cache(url, output = FormType.EDFORM) {
  if (cachedUrls.includes(url)) {
    let response = claim;
    if (output === FormType.HEADLESS_FORM) {
      response = claimAF;
    }

    return new Response(JSON.stringify(response), { status: 200, headers: { 'Content-Type': 'application/json' } });
  }
  return null;
}

/**
 * This is the main function
 * @param {Request} request the request object (see fetch api)
 * @param {UniversalContext} context the context of the universal serverless function
 * @returns {Response} a response
 */
async function run(request, context) {
  const { url, options = {}, output = FormType.EDFORM } = context.data;
  const { userAgent = '' } = options;
  if (isURL(url)) {
    const cached = cache(url, output);
    if (cached) {
      return cached;
    }
    const content = await getContent(url, userAgent);
    if (content) {
      const forms = await getAllForms(content, options, output);
      return new Response(JSON.stringify(forms), { status: 200, headers: { 'Content-Type': 'application/json' } });
    } else {
      return new Response('Failed to fetch content from Url, try disabling CORS', {
        status: 400,
      });
    }
  } else {
    return new Response('Missing or invalid url', {
      status: 400,
    });
  }
}

export const main = wrap(run)
  .with(status)
  .with(bodyData)
  .with(addCommonResponseHeadersWrapper)
  .with(logger.trace)
  .with(logger);

export * from './FormsImporter.js';
