import Logging from "@hibas123/nodelogging";
import * as fs from "fs";

let private_key: string;
let rsa: RSA;
export function sign(message: Buffer): Buffer {
   return rsa.sign(message, "buffer");
}

export function verify(message: Buffer, signature: Buffer): boolean {
   return rsa.verify(message, signature);
}

export let public_key: string;

import * as jwt from "jsonwebtoken";

export function createJWT(payload: any, options: jwt.SignOptions) {
   return new Promise<string>((resolve, reject) => {
      return jwt.sign(payload, private_key, options, (err, token) => {
         if (err) reject(err);
         else resolve(token);
      });
   });
}

export async function validateJWT(data: string) {
   return new Promise<any>((resolve, reject) => {
      jwt.verify(data, public_key, (err, valid) => {
         if (err) reject(err);
         else resolve(valid);
      });
   });
}

let create = false;
if (fs.existsSync("./keys")) {
   if (fs.existsSync("./keys/private.pem")) {
      if (fs.existsSync("./keys/public.pem")) {
         Logging.log("Using existing private and public key");
         private_key = fs.readFileSync("./keys/private.pem").toString("utf8");
         public_key = fs.readFileSync("./keys/public.pem").toString("utf8");

         if (!private_key || !public_key) {
            create = true;
         }
      } else create = true;
   } else create = true;
} else create = true;

import RSA from "node-rsa";

if (create === true) {
   Logging.log("Started RSA Key gen");
   let rsa = new RSA({ b: 4096 });
   private_key = rsa.exportKey("private");
   public_key = rsa.exportKey("public");

   if (!fs.existsSync("./keys")) {
      fs.mkdirSync("./keys");
   }
   fs.writeFileSync("./keys/private.pem", private_key);
   fs.writeFileSync("./keys/public.pem", public_key);
   Logging.log("Key pair generated");
}

rsa = new RSA(private_key, "private");
rsa.importKey(public_key, "public");
