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;
    }

    let resultObject = await postData("/register", {
        username: registerForm.regUser.value,
        password: registerForm.regPass.value,
        role: registerForm.regRole.value
    });
    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";
    }
};
