import { knex } from "../lib/ormish.js";
import { question } from "readline-sync";
import { main as devsvc } from "./devsvc.js";
import { glob, exec, mkdir, copy } from "../lib/builderator.js";
import path from "path";
import { existsSync as exists } from "fs";

export const description = "Initializes a fresh bando project";

export const options = [
  ["--force", "DANGER! overwite config files with templates"],
  ["--templates", "what to use as a template directory", "./commands/templates"],
];

// I did have chalk here but not sure so removed it for now
const warn = console.warn;
const good = console.log;
const error = console.error;

const dirs = ["./debug/emails","./debug/errors","./secrets"];

const copy_templates = (templates, force) => {
  good("Copying templates to your project. You can commit these to git.");

  const source_files = glob(`${templates}/**/*`);

  for(let template of source_files) {
    // need to add a . for the path to be local
    const dest = "." + template.slice(templates.length);

    if(force || !exists(dest)) {
      good(template, "->", dest);
      copy(template, dest);
    } else {
      good("SKIPPING", dest);
    }
  }
}

export const main = async (opts) => {
  good("Creating configuration directories.");

  dirs.forEach(d => mkdir(d));

  warn("!!! WARNING!: Do not add the contents of secrets to your git repository.");

  copy_templates(opts.templates, opts.force);

  good("Starting redis for your OS so you can register an admin.");
  devsvc({start: true, noexit: true});

  //good("Generating the documentation first time...");
  // exec("npm run docs");
  //good("Documentation done.");

  good("Migrating your database just in case.");
  exec("npm run knex migrate:latest")
  good("In another window start the app server with: npm run DANGER_ADMIN");

  question("When you're done hit ENTER.");

  // open the registration page
  const url = "http://127.0.0.1:5001/client/#/register/"
  good(`Opening ${url}`);

  if(process.platform === "win32") {
    exec(`start ${url}`);
  } else if(process.platform === "darwin") {
    exec(`open ${url}`);
  } else {
    warn(`\nOn linux you just open the link yourself:\n${url}\n`);
  }

  question("Register your admin user and hit ENTER.");

  // run a sql command to update the first user to admin
  warn("Changing user id 1 to admin: true");

  let result = await knex("user").where({id: 1}).update({admin: 1});

  if(result !== 1) {
    error(`Expected to only change one record in user but changed ${result}. You'll have to change your user to admin manually.`);
  } else {
    good("Updated the user at id 1 to have admin access.");
  }

  knex.destroy();

  good("FINISHED!  You can now edit the project to make what you want.");

  process.exit(0);
}
