/**
 * Step 1 — Coletar credenciais OAuth do Fluig
 */

const { R, B, DIM, AMBER, MUTED } = require("../colors");
const { stepHeader, boxTop, boxMid, boxSep, boxBot, info, print } = require("../banner");

async function collectCredentials() {
  const { default: inquirer } = await import("inquirer");

  stepHeader(2, 5, "Configuracao do servidor Fluig");

  boxTop();
  boxMid(`${AMBER}${B}Voce precisara de:${R}`, undefined, "left");
  boxSep();
  boxMid(`${MUTED}URL do servidor Fluig${R}`, undefined, "left");
  boxMid(`${MUTED}Consumer Key + Consumer Secret  ${DIM}(OAuth App)${R}`, undefined, "left");
  boxMid(`${MUTED}Access Token + Token Secret     ${DIM}(Painel OAuth)${R}`, undefined, "left");
  boxSep();
  boxMid(`${DIM}Painel de Controle \u2192 OAuth \u2192 Aplicacoes${R}`, undefined, "left");
  boxBot();
  print("");

  const { skipSetup } = await inquirer.prompt([
    {
      type: "confirm",
      name: "skipSetup",
      message: "Pular configuracao de credenciais? (modo somente dev tools)",
      default: false,
    },
  ]);

  if (skipSetup) {
    info("Modo somente dev tools — credenciais ignoradas.");
    return {
      FLUIG_SERVER: "",
      FLUIG_CONSUMER_KEY: "",
      FLUIG_CONSUMER_SECRET: "",
      FLUIG_ACCESS_TOKEN: "",
      FLUIG_TOKEN_SECRET: "",
      FLUIG_VERIFY_SSL: "true",
    };
  }

  const answers = await inquirer.prompt([
    {
      type: "input",
      name: "FLUIG_SERVER",
      message: "URL do servidor Fluig",
      default: "https://seu-servidor.fluig.com",
      validate: (v) =>
        /^https?:\/\/.+/.test(v) ? true : "URL deve comecar com http:// ou https://",
    },
    {
      type: "input",
      name: "FLUIG_CONSUMER_KEY",
      message: "Consumer Key",
      validate: (v) => (v.trim() ? true : "Consumer Key e obrigatoria"),
    },
    {
      type: "password",
      name: "FLUIG_CONSUMER_SECRET",
      message: "Consumer Secret",
      mask: "*",
      validate: (v) => (v.trim() ? true : "Consumer Secret e obrigatorio"),
    },
    {
      type: "input",
      name: "FLUIG_ACCESS_TOKEN",
      message: "Access Token",
      validate: (v) => (v.trim() ? true : "Access Token e obrigatorio"),
    },
    {
      type: "password",
      name: "FLUIG_TOKEN_SECRET",
      message: "Token Secret",
      mask: "*",
      validate: (v) => (v.trim() ? true : "Token Secret e obrigatorio"),
    },
  ]);

  answers.FLUIG_SERVER = answers.FLUIG_SERVER.replace(/\/+$/, "");

  // Perguntar sobre verificacao SSL para servidores HTTPS
  if (/^https:\/\//i.test(answers.FLUIG_SERVER)) {
    const { verifySSL } = await inquirer.prompt([
      {
        type: "confirm",
        name: "verifySSL",
        message: "Verificar certificado SSL? (desative para certificados auto-assinados)",
        default: true,
      },
    ]);
    answers.FLUIG_VERIFY_SSL = verifySSL ? "true" : "false";
  } else {
    answers.FLUIG_VERIFY_SSL = "false";
  }

  return answers;
}

module.exports = { collectCredentials };
