// Copyright (c) 2020,2021, StepZen, Inc.

const bodyParser = require("body-parser");
const cors = require("cors");
const express = require("express");
const fs = require("fs");

const openBrowser = require("./utils/open-browser");

const details = require("./api/details");
const generate = require("./api/generate");
const proxy = require("./api/proxy");

module.exports = async ({
  account,
  adminkey,
  domain = "stepzen.io",
  generators = null,
  port = 5000,
  workspace,
}) => {
  const app = express();

  app.use(bodyParser.json());
  app.use(cors());

  app.use(express.static(`${__dirname}/../ui/build`));
  app.use((req, res, next) => {
    req.account = account;
    req.adminkey = adminkey;
    req.domain = domain;
    req.generators = generators;
    req.workspace = workspace;
    next();
  });

  app.get("/api/details", details);
  app.all("/api/generate/:action", generate);
  app.post("/api/graphql", proxy);

  const dashboard = fs.readFileSync(
    `${__dirname}/../ui/build/index.html`,
    "utf8"
  );
  app.get("*", (req, res) => res.send(dashboard));

  const open = () =>
    openBrowser(`http://localhost:${port}/${workspace.endpoint}`);

  const start = async () =>
    new Promise((resolve) => {
      app.listen(port, () => {
        resolve();
      });
    });

  return {
    app,
    open,
    start,
  };
};
