import crypto from "crypto";
const algorithm = "aes-256-gcm";

const secretKey = Buffer.from(
  process.env.UUID_SECRET_KEY!,
  "hex"
);


var secret_shifter = 5 

export function EncodeUUID(UUID:string) {

    var EncodeUUID = ""
    
    for (var i=0; i<UUID.length; i++){
        var value = UUID.charCodeAt(i) + secret_shifter

        var value2 = String.fromCharCode(value)

        EncodeUUID += value2
    
    }

    return EncodeUUID
}

export function DecodeUUID(decodedUUID: string){

    var UUID = "" 

    for (var i=0; i<decodedUUID.length; i++){
        
        var value = decodedUUID.charCodeAt(i) - secret_shifter

        var value2 = String.fromCharCode(value)

        UUID += value2
    }

    return UUID

}



export function encryptUUID(uuid: string): string {
  const iv = crypto.randomBytes(12);

  const cipher = crypto.createCipheriv(
    algorithm,
    secretKey,
    iv
  );

  const encrypted = Buffer.concat([
    cipher.update(uuid, "utf8"),
    cipher.final(),
  ]);

  const authTag = cipher.getAuthTag();

  return Buffer.concat([
    iv,
    authTag,
    encrypted,
  ]).toString("base64url");
}

export function decryptUUID(token: string): string {
  const buffer = Buffer.from(token, "base64url");

  const iv = buffer.subarray(0, 12);
  const authTag = buffer.subarray(12, 28);
  const encrypted = buffer.subarray(28);

  const decipher = crypto.createDecipheriv(
    algorithm,
    secretKey,
    iv
  );

  decipher.setAuthTag(authTag);

  const decrypted = Buffer.concat([
    decipher.update(encrypted),
    decipher.final(),
  ]);

  return decrypted.toString("utf8");
}