// 轻量静态文件 + API 代理服务器
// PM2 启动: node serve-proxy.js
const http = require('http');
const fs = require('fs');
const path = require('path');

const PORT = process.env.FRONTEND_PORT || 5173;
const API_TARGET = process.env.API_TARGET || 'http://127.0.0.1:3000';
const STATIC_DIR = path.join(__dirname, 'apps/admin/dist');

const MIME = {
  '.html': 'text/html; charset=utf-8',
  '.js': 'application/javascript',
  '.css': 'text/css',
  '.json': 'application/json',
  '.png': 'image/png',
  '.svg': 'image/svg+xml',
  '.ico': 'image/x-icon',
  '.woff2': 'font/woff2',
};

function serveStatic(res, filePath) {
  const ext = path.extname(filePath);
  const mime = MIME[ext] || 'application/octet-stream';
  try {
    const content = fs.readFileSync(filePath);
    res.writeHead(200, { 'Content-Type': mime, 'Cache-Control': ext === '.html' ? 'no-cache' : 'public, max-age=604800' });
    res.end(content);
  } catch {
    // SPA fallback: return index.html
    const index = fs.readFileSync(path.join(STATIC_DIR, 'index.html'));
    res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
    res.end(index);
  }
}

const server = http.createServer((req, res) => {
  // API 代理
  if (req.url.startsWith('/api/')) {
    const opts = {
      hostname: '127.0.0.1',
      port: 3000,
      path: req.url,
      method: req.method,
      headers: { ...req.headers, host: '127.0.0.1:3000' },
    };
    const proxy = http.request(opts, (proxyRes) => {
      res.writeHead(proxyRes.statusCode, proxyRes.headers);
      proxyRes.pipe(res);
    });
    proxy.on('error', () => {
      res.writeHead(502);
      res.end('API unavailable');
    });
    req.pipe(proxy);
    return;
  }

  // 静态文件
  const urlPath = req.url === '/' ? '/index.html' : req.url.split('?')[0];
  const safePath = path.normalize(urlPath).replace(/^(\.\.(\/|\\|$))+/, '');
  serveStatic(res, path.join(STATIC_DIR, safePath));
});

server.listen(PORT, () => {
  console.log(`Frontend proxy running on http://0.0.0.0:${PORT} → API: ${API_TARGET}`);
});
