// Copyright (c) 2020,2021, StepZen, Inc.
const graphqlQuery = require("../utils/graphql-query");

const QUERIES = {
  CREATE: (id, details = {}) => `
    query {
      create(id: "${id}", details: ${JSON.stringify(details)}) {
        content
        name
      }
    }
  `,
  CONFIGURE: (id, details = {}) => `
    query {
      configure(id: "${id}", details: ${JSON.stringify(details)}) {
        answers
        errors
        questions
        status
      }
    }
  `,
  ENGINES: (beta = false) => `
    query {
      engines(beta: true) {
        categories
        description
        id
        image
        name
      }
    }
  `,
};

const generate = async (req, res) => {
  const action = req.params.action;
  const { onStart, onImport } = req.generators;
  const { version = "" } = req.cli;

  if (action === "create") {
    const { id, details } = req.query;
    const { data } = await graphqlQuery({
      ...req,
      query: QUERIES.CREATE(id, details),
    });
    const imported = await onImport(id, data.create);
    return res.json(imported);
  }

  if (action === "configure") {
    const { details, id } = req.query;
    const result = await graphqlQuery({
      ...req,
      query: QUERIES.CONFIGURE(id, details),
    });
    return res.json(result?.data?.configure);
  }

  if (action === "engines") {
    await onStart();
    const result = await graphqlQuery({
      ...req,
      query: QUERIES.ENGINES(version.includes("beta")),
    });
    return res.json(result?.data?.engines);
  }

  res.status(404).send();
};

module.exports = generate;
