const bcrypt = require("bcrypt");
const crypto = require("crypto");
const { format } = require("date-fns");
const { models } = require("../db/db");
const { User } = models;
const jwt = require("jsonwebtoken");
require("dotenv").config();

async function main() {
  const password = crypto.randomBytes(32).toString("hex");
  const username = process.argv[2];

  const salt = await bcrypt.genSalt(10);
  const passwordEncrypted = await bcrypt.hash(password, salt);

  const email = `${username}@2weemail.fyi`;

  const user = await models.User.query().insert({
    username: username,
    password: passwordEncrypted,
    email: email,
    is_admin: Boolean(true),
    is_active: Boolean(true),
    created: format(new Date(), "yyyy-MM-dd HH:mm:ss"),
    modified: format(new Date(), "yyyy-MM-dd HH:mm:ss")
  });

  const token = jwt.sign(
    {
      id: user.id,
      username: username,
      is_admin: Boolean(true),
      email: email,
    },
    process.env.JWT_SECRET,
    { expiresIn: "40y" }
  );

  await models.User.query()
    .patch({
      api_key: token,
    })
    .where('id', user.id);

  console.log({ token, password });
}

main();