/**
 * Crawlie fetch backend — Vercel serverless function
 * ----------------------------------------------------
 * Alternative to the Cloudflare Worker, for people already using Vercel.
 *
 * DEPLOY:
 *   1. Create a new Vercel project (or use an existing one).
 *   2. Put this file at api/fetch.js in that project.
 *   3. Deploy. Your endpoint will be https://<your-project>.vercel.app/api/fetch
 *   4. Paste that URL into Crawlie's "Use your own fetch backend" box
 *      (shown on the report page when a scan fails) and save.
 *
 * Free tier covers this comfortably for personal use.
 * Same honest limits as the Cloudflare Worker apply — see worker.js.
 */
export default async function handler(req, res) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type');

  if (req.method === 'OPTIONS') return res.status(200).end();

  const target = req.query.url;
  if (!target) return res.status(400).send('Missing url parameter');

  let targetUrl;
  try {
    targetUrl = new URL(target);
  } catch (e) {
    return res.status(400).send('Invalid URL');
  }
  if (targetUrl.protocol !== 'http:' && targetUrl.protocol !== 'https:') {
    return res.status(400).send('Only http/https URLs are allowed');
  }

  try {
    const upstream = await fetch(targetUrl.toString(), {
      redirect: 'follow',
      headers: {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Language': 'en-US,en;q=0.9',
      },
    });
    const html = await upstream.text();
    res.setHeader('Content-Type', 'text/html; charset=utf-8');
    res.status(upstream.status).send(html);
  } catch (e) {
    res.status(502).send('Upstream fetch failed: ' + (e && e.message ? e.message : 'unknown error'));
  }
}

