/**
 * Standalone API proxy for React development.
 * Equivalent to Angular's proxy.conf.json — proxies /api/* and /flights/*
 * to flights.test.aeroflot.ru.
 *
 * Supports the system HTTPS proxy (e.g., GOST at 127.0.0.1:8888)
 * via https-proxy-agent when HTTPS_PROXY env var is set.
 *
 * Usage:
 *   node scripts/api-proxy.mjs          # port 4201
 *   PORT=3001 node scripts/api-proxy.mjs
 *
 * Then set API_BASE_URL=http://localhost:4201/api in .env or
 * use the default in src/env/index.ts.
 */
import express from "express";
import { createProxyMiddleware } from "http-proxy-middleware";
import { HttpsProxyAgent } from "https-proxy-agent";

const TARGET = "https://flights.test.aeroflot.ru";
const PORT = parseInt(process.env.PORT || "4201", 10);
const SYSTEM_PROXY = process.env.https_proxy || process.env.HTTPS_PROXY || "";

const app = express();

// CORS for browser requests from localhost:8080
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", "*");
  if (_req.method === "OPTIONS") {
    res.sendStatus(204);
    return;
  }
  next();
});

// Build proxy options — use https-proxy-agent if system proxy is set
const proxyOptions = {
  target: TARGET,
  changeOrigin: true,
  secure: false,
  logLevel: "warn",
};

if (SYSTEM_PROXY) {
  proxyOptions.agent = new HttpsProxyAgent(SYSTEM_PROXY);
  console.log(`Using system proxy: ${SYSTEM_PROXY}`);
}

// Proxy /api/* and /flights/*
app.use(
  ["/api", "/flights"],
  createProxyMiddleware(proxyOptions),
);

app.listen(PORT, () => {
  console.log(`API proxy listening on http://localhost:${PORT}`);
  console.log(`Forwarding /api/* and /flights/* to ${TARGET}`);
  console.log(`React app should set API_BASE_URL=http://localhost:${PORT}/api`);
});
