/* eslint-disable unicorn/no-process-exit */
/* eslint-disable n/no-process-exit */
/* eslint-disable perfectionist/sort-imports */
/* eslint-disable perfectionist/sort-objects */
import express from "express";
import inquirer from "inquirer";
import log from "../util/log.js";
import Conf from "conf";
import api from "../aws/index.js";
import path, { dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import waitForState from "../util/asyncWait.js";
const __dirname = dirname(fileURLToPath(import.meta.url));
const DEFAULT_NAME = 'campfire';
const config = new Conf({ projectName: DEFAULT_NAME });
const app = express();
const port = 3000;
let server;
app.use("/register", express.static(path.join(__dirname, "/../../public")));
function terminateServer() {
    log.info(`Closing server on port ${[port]}.`);
    server.close(() => log.info("Server closed."));
}
async function retrieveAppInfo(code) {
    const URL = `https://api.github.com/app-manifests/${code}/conversions`;
    const response = await fetch(URL, { method: "POST" });
    const body = await response.json();
    try {
        api.clients.secrets = await api.initializeSecretsClient({ region: config.get("AWS_REGION") });
        await api.createSecrets(body);
        config.set("APP_REGISTERED", true);
        log.info("Your GitHub App secrets have been stored in AWS Secrets Manager.");
        terminateServer();
    }
    catch (error) {
        log.error(error);
        terminateServer();
        process.exit(1);
    }
}
app.get("/", (req, res) => {
    if (req.query.code) {
        retrieveAppInfo(req.query.code);
        res.sendFile(path.join(__dirname, "/../../public/redirect.html"));
    }
    else {
        res.sendFile(path.join(__dirname, "/../../public/fail.html"));
    }
});
async function main() {
    let registerPage;
    let orgName;
    const answer = await inquirer.prompt([
        {
            type: "list",
            name: "userType",
            message: "Are you installing the app as a personal user or an organization?",
            choices: ["Personal", "Organization"],
        },
    ]);
    if (answer.userType === "Organization") {
        const answer = await inquirer.prompt([
            {
                type: "input",
                name: "orgName",
                message: "Enter the name of your organization: ",
            },
        ]);
        orgName = answer.orgName;
        registerPage = `org.html`;
    }
    else {
        registerPage = `user.html`;
    }
    log.info(`Installing as a ${answer.userType}`);
    log.info(`Please head over to http://localhost:${port}/register/${registerPage}${orgName ? `?org=${orgName}` : ""} to complete the process.`);
    server = app.listen(port);
    await waitForState({
        startMsg: `Waiting for the app to be registered on PORT ${port}\n`,
        successMsg: 'App registeration completed!',
        desiredState: true,
        describeFn: () => Boolean(config.get("APP_REGISTERED", false)),
        describeArgs: { StackName: DEFAULT_NAME },
        resCallback: response => response,
    });
}
export default main;
