const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const path = require('path');

const app = express();
const PORT = 8081;

// CORS 中间件
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  if (req.method === 'OPTIONS') {
    return res.sendStatus(200);
  }
  next();
});

// API 代理：必须在静态文件服务之前，将 /api 请求代理到 cattletrack.aiotagro.com
app.use('/api', createProxyMiddleware({
  target: 'https://cattletrack.aiotagro.com',
  changeOrigin: true,
  secure: false,
  pathRewrite: {
    '^/api': '/api', // 保持 /api 前缀
  },
  onProxyReq: (proxyReq, req, res) => {
    console.log(`[代理] ${req.method} ${req.url} -> https://cattletrack.aiotagro.com${req.url}`);
    // 确保请求方法正确转发
    proxyReq.method = req.method;
  },
  onProxyRes: (proxyRes, req, res) => {
    console.log(`[代理响应] ${req.method} ${req.url} - 状态码: ${proxyRes.statusCode}`);
  },
  onError: (err, req, res) => {
    console.error('[代理错误]', err);
    res.status(500).json({ error: '代理请求失败', details: err.message });
  }
}));

// 静态文件服务：提供 datav 目录下的文件
app.use(express.static(__dirname));

app.listen(PORT, () => {
  console.log(`服务器已启动: http://127.0.0.1:${PORT}`);
  console.log(`请访问: http://127.0.0.1:${PORT}/index.html`);
});

