import { postData } from "./client.js";

const registerForm = document.getElementById("registerForm");

const error = document.querySelector(".error");
const errorMessage = document.querySelector(".error p");
const success = document.querySelector(".success");

if (registerForm) registerForm.onsubmit = async e => {
    e.preventDefault();

    if (registerForm.regPass.value !== registerForm.regVerify.value) {
        error.style.display = "flex";
        errorMessage.innerHTML = "Passwords must match";
        return;
    }

    const salt = window.crypto.getRandomValues(new Uint8Array(16));


    const { authenticationKeyString, encryptionKeyObject } = await generateKeys(registerForm.regPass.value, salt);

    console.log(authenticationKeyString);
    console.log(encryptionKeyObject);


    let resultObject = await postData("/register", {
        username: registerForm.regUser.value,
        password: authenticationKeyString,
        role: registerForm.regRole.value,
        salt: convertBufferToHex(salt)
    });
    if (resultObject.message.includes("User registered")) {
        error.style.display = "none";
        success.style.display = "flex";
    } else {
        errorMessage.innerHTML = resultObject.message;
        error.style.display = "flex";
    }
    if (resultObject.success === true) {
        window.location.href = "/login";
    }
};

async function generateKeys(password, salt) {
    const encoder = new TextEncoder();

    const base = await window.crypto.subtle.importKey(
        "raw",
        encoder.encode(password),
        "PBKDF2",
        false,
        ["deriveBits", "deriveKey"]
    );

    const authSalt = new Uint8Array([...salt, ...encoder.encode("auth")]);
    const authKeyBits = await window.crypto.subtle.deriveBits(
        {
            name: "PBKDF2",
            salt: authSalt,
            iterations: 100000,
            hash: "SHA-256"
        },
        base,
        256
    );

    const encryptionSalt = new Uint8Array([...salt, ...encoder.encode("enc")]);
    const encryptionKey = await window.crypto.subtle.deriveKey(
        {
            name: "PBKDF2",
            salt: encryptionSalt,
            iterations: 100000,
            hash: "SHA-256"
        },
        base,
        { name: "AES-GCM", length: 256 },
        false,
        ["encrypt", "decrypt"]
    );

    console.log(convertBufferToHex(authKeyBits));
    console.log(encryptionKey);

    return {
        authenticationKeyString: convertBufferToHex(authKeyBits),
        encryptionKeyObject: encryptionKey
    };
}

function convertBufferToHex(buffer) {
  const bytes = new Uint8Array(buffer);
  return Array.from(bytes)
    .map(byte => byte.toString(16).padStart(2, '0'))
    .join('');
}

