<script lang="ts">
  import * as svelteForms from "svelte-forms";
  import * as validators from "svelte-forms/validators";
  import { setCookie, removeCookie } from "typescript-cookie";
  import { operationStore, mutation, gql } from "@urql/svelte";

  import { session } from "$app/stores";
  import { goto } from "$app/navigation";
  import * as cookieNames from "$lib/cookieNames";
  import type { LoginPayload } from "$lib/graphql";

  const username = svelteForms.field("username", undefined, [
    validators.required(),
  ]);
  const password = svelteForms.field("password", undefined, [
    validators.required(),
  ]);
  const loginForm = svelteForms.form(username, password);

  interface Data {
    login: LoginPayload;
  }

  interface Vars {
    username: string;
    password: string;
  }

  const loginStore = operationStore<Data, Vars>(gql`
    mutation Login($username: String!, $password: String!) {
      login(username: $username, password: $password) {
        token
      }
    }
  `);
  const login = mutation(loginStore);

  async function submit(): Promise<void> {
    await login({
      username: $username.value as string,
      password: $password.value as string,
    });

    if ($loginStore.error) {
      removeCookie(cookieNames.TOKEN);
    } else {
      $session.user.token = $loginStore.data.login.token;
      setCookie(cookieNames.TOKEN, $session.user.token, {
        expires: 1,
      });
      goto("/");
    }
  }
</script>

<form on:submit|preventDefault={submit}>
  <label for="username">Benutzernane (Moodle):</label>
  <br />
  <input type="text" id="username" bind:value={$username.value} />
  <br />
  <label for="password">Kennwort:</label>
  <br />
  <input type="password" id="password" bind:value={$password.value} />

  <br /><br />

  <button type="submit" disabled={!$loginForm.valid}>Login</button>

  <br />

  {#if $loginStore.error}
    <p style="color: red;">{$loginStore.error.message}</p>
  {/if}
</form>
