var express = require('express');
var router = express.Router();
const fetch = require('node-fetch');
const config = require('../config/app');

// 代理请求的中间件
router.use('/', async (req, res) => {
  console.log(`proxy req.url = ${req.url}`);
  const targetUrl = `${config.resHost}${req.url}`; // 替换为目标服务器的 URL
  console.log(`targetUrl = ${targetUrl}`);

  const method = req.method;
  const headers = {
    ...req.headers,
    // 可能需要根据目标服务器的要求调整或添加请求头
  };

  // 如果请求包含请求体（例如 POST 请求），则读取它
  let body;
  if (req.method === 'POST' || req.method === 'PUT') {
    body = await getRawBody(req); // 使用 getRawBody 函数读取请求体
  }

  try {
    const response = await fetch(targetUrl, {
      method,
      headers,
      body,
    });

    // 在这里添加 CORS 响应头
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');

    // 将目标服务器的响应转发给客户端
    const responseData = await response.buffer(); // 获取响应的 Buffer
    res.status(response.status).send(responseData);
  } catch (error) {
    // 处理错误，并将错误信息返回给客户端
    console.error('Proxy error:', error);
    res.status(500).send('Internal Server Error');
  }
});

// 辅助函数：读取请求体的原始数据
async function getRawBody(req) {
  return new Promise((resolve, reject) => {
    let chunks = [];
    req.on('data', (chunk) => {
      chunks.push(chunk);
    });
    req.on('end', () => {
      resolve(Buffer.concat(chunks));
    });
    req.on('error', reject);
  });
}

module.exports = router;