<script setup lang="ts">
import { z } from "zod";
import type { AuthFormField, FormSubmitEvent } from "@nuxt/ui";

definePageMeta({
  middleware: () => {
    const { loggedIn } = useUserSession();
    if (loggedIn.value) return navigateTo("/dashboard");
  },
});

const fields: AuthFormField[] = [
  { name: "username", type: "text", label: "Username", required: true },
  { name: "password", type: "password", label: "Password", required: true },
];

const schema = z.object({
  username: z.string({ error: "Required" }),
  password: z.string({ error: "Required" }),
});

type Schema = z.output<typeof schema>;

const { fetch: fetchSession } = useUserSession();
const error = ref<string | null>(null);
const loading = ref(false);

const onSubmit = async (event: FormSubmitEvent<Schema>) => {
  error.value = null;
  loading.value = true;
  try {
    await $fetch("/api/auth/sign-in", { method: "POST", body: event.data });
    await fetchSession();
    await navigateTo("/dashboard");
  } catch (e) {
    error.value = getApiError(e);
  } finally {
    loading.value = false;
  }
};
</script>

<template>
  <div class="flex items-center justify-center min-h-screen">
    <UPageCard class="w-full max-w-sm">
      <UAuthForm
        title="Sign In"
        :fields="fields"
        :schema="schema"
        :loading="loading"
        @submit="onSubmit"
      >
        <template v-if="error" #validation>
          <UAlert color="error" icon="i-lucide-circle-alert" :title="error" />
        </template>
      </UAuthForm>
    </UPageCard>
  </div>
</template>
