// for SG test

const express = require("express");
const { createProxyMiddleware } = require("http-proxy-middleware");
const path = require("path");
const morgan = require("morgan");
const fs = require("fs");

const app = express();
const port = 3000;

app.use(morgan("dev")); // for log


const TARGET = "http://localhost:18080";
app.use(
  "/api",
  createProxyMiddleware({
    target: TARGET,
    changeOrigin: true,
    pathRewrite: (path, req) => {
      console.log("pathRewrite, path: ", path);
      //console.log("pathRewrite, req.url: ", req.url);
      //console.log("pathRewrite, req.headers: ", req.headers);
      let convertedUrl = `/api${path}`;
      console.log(`pathRewrite, convertedUrl: ${TARGET}${convertedUrl}`);
      return convertedUrl;
    },
    //fuck!!!
    //
    logLevel: "debug",
    logProvider: () => console,
    onError: (err, req, res) => {
      console.error("onError, err: ", err);
    },
    onProxyReq: (proxyReq, req, res) => {
      console.log(">>> Sending request to target:");
      console.log("onProxyReq, req.originalUrl: ", req.originalUrl);
      console.log("onProxyReq, proxyReq.getHeader('host'): ", proxyReq.getHeader("host"));
      console.log("onProxyReq, proxyReq.path: ", proxyReq.path);
      console.log("onProxyReq, target url: ", `${proxyReq.agent.protocol}//${proxyReq.getHeader("host")}${proxyReq.path}`);
    },
    onProxyRes: (proxyRes, req, res) => {
      console.log("<<< Response received from target:");
      console.log("onProxyRes, proxyRes.statusCode: ", proxyRes.statusCode);
    },
    //
    //fuck!!!
  })
);

app.use(
  express.static(path.join(__dirname, "out"), {
    maxAge: 0,
    etag: false,
    lastModified: false,
    redirect: false
  })
);

app.use((req, res, next) => {
  console.log("received request", req.method, req.url);

  const reqPath = req.path;
  const htmlFilePath = path.join(__dirname, "out", reqPath + ".html");

  if (fs.existsSync(htmlFilePath)) {
    res.sendFile(htmlFilePath);
  } else {
    next();
  }
});

app.listen(port, () => {
  console.log(`Static site with proxy running at http://localhost:${port}`);
});
