<script setup lang="ts">
/* global $fetch */
import { ref } from 'vue';
import { type NuxtError } from 'nuxt/app';
import { navigateTo, useFetch, definePageMeta } from '#imports';

import EntryEditor, { type fieldDefinition } from '~/components/entryEditor.vue';
import Alerts, { type AlertData } from '~/components/alerts.vue';

const editorFields: Array<fieldDefinition> = [
  { key: "username", type: "text", label: "Username", optional: false },
  { key: "password", type: "text", label: "Password", optional: false },
  { key: "email", type: "text", label: "email", optional: false },
];

const formValue = ref<any>({});
const alerts = ref<Array<AlertData>>([]);

definePageMeta({
  layout: false,
});

async function submit() {
  try {
    await $fetch("/api/firstRun", {
      body: formValue.value,
      method: "POST",
    });
    await navigateTo("/login");
  } catch (e) {
    console.log(e);
    alerts.value.push({ text: (e as NuxtError).data.message });
  }
}

if (!(await useFetch("/api/firstRun")).data.value)
  await navigateTo("/login");
</script>

<template>
  <Alerts :alerts="alerts" />
  <VCard max-width="450px" class="mx-auto mt-16" variant="outlined">
    <template #title>
      Initial setup
    </template>
    <template #text>
      <p>
        It looks like you've run the server with an empty or uninitialized database or with database without any users.<br>
        Below you can initialize the database register your first user and.
      </p><br>
      <EntryEditor
        :fields="editorFields"
        @update-sub-model-value="(k, v) => { formValue[k] = v }"
      />
    </template>
    <template #actions>
      <VBtn color="primary" @click="submit">
        Initialize
      </VBtn>
    </template>
  </VCard>
</template>
