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

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 _predicates = require("./api/predicates");
const proxy = require("./api/proxy");

module.exports = async ({
  account,
  adminkey,
  apikey,
  cli = { version: "" },
  domain = "stepzen.io",
  generators,
  port = 5000,
  predicates = {
    available: false,
    enabled: false,
    onTogglePredicates: async () => {},
  },
  workspace,
}) => {
  const app = express();

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

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

  app.all("/api/predicates", _predicates);
  app.get("/api/details", details);
  app.get("/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,
  };
};
