/// <reference lib="dom" />

import { loginApi } from "./shared.bundle.ts";

const form = document.getElementById("loginForm") as HTMLFormElement;
const passwordInput = document.getElementById(
    "passwordInput",
) as HTMLInputElement;
const errDiv = document.getElementById("errDiv") as HTMLDivElement;

form.addEventListener("submit", async (e) => {
    e.preventDefault();

    const password = passwordInput.value;

    const res = (await loginApi.makeRequest({ password }, {})).flatten();

    if (res.isErr()) {
        if (res.error.type === "RequestValidationError") {
            errDiv.innerText = res.error.msg;
        }
    } else {
        if (!res.value.isMatch) {
            errDiv.innerText = "invalid password";
        } else {
            window.location.href = "/";
        }
    }
});
