<script lang="ts">
    import { redirect } from "@sveltejs/kit";


    let error = $state("")

    async function loginButton(event: SubmitEvent) {
        
        event.preventDefault()

        const form = event.target as HTMLFormElement
        
        const username : string | null = form.username.value
        const password : string | null = form.password.value

        // UGLY: standardize
        const jsonPayload = {
            username: username,
            password: password
        }

        const res = await fetch(
            "/api/login",
            {
                method: "POST",
                body: JSON.stringify(jsonPayload)
            }
        )

        if (res.status != 200) {
            error = res.statusText
        }

        redirect(302, "/app/program")

    }

</script>

<h1>Login</h1>


<form action="" onsubmit={loginButton}  >
<input name="username" type="text" required minlength="4" autocomplete="username" />
<input name="password" type="password" required minlength="8" autocomplete="current-password" />
<input type="submit">
</form>

{#if (error.length !== 0)}
    <span>{error}</span>
{/if}


