<template>
  <SiteTitle :title="$t('addFirstUser')" />
  <div :class="$q.screen.width > 600 ? 'q-ma-xl q-pa-xs' : 'q-ma-none q-pa-none'">
    <q-card :class="$q.screen.width > 600 ? 'q-ma-xl q-pa-xl' : 'q-gutter-md'">
      <q-form ref="form">
        <div class="q-pt-md">
          <div class="row justify-center q-gutter-md">
            <q-input
              class="col-6 required"
              :label="$t('user')"
              filled
              :lazy-rules="false"
              :rules="[(val) => !!val || $t('userIsRequired')]"
              v-model="localUser.user"
              autofocus
            ></q-input>
            <q-input
              class="col-6 required"
              :label="$t('email')"
              filled
              :lazy-rules="false"
              :rules="[(val) => !!val || $t('emailIsRequired')]"
              v-model="localUser.email"
            ></q-input>
            <EnterNewPassword class="col-6 required" v-model:password="localUser.password!" />
          </div>
          <div class="row justify-center">
            <q-btn class="q-ma-md" color="primary" no-caps @click="save">{{ $t('save') }}</q-btn>
          </div>
        </div>
      </q-form>
    </q-card>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { appApi } from 'src/boot/axios';
import type { User } from 'src/vueLib/models/users';
import { useNotify } from 'src/vueLib/general/useNotify';
import { validateQForm } from 'src/vueLib/utils/validation';
import { i18n } from 'src/boot/lang';
import { DefaultSettings } from 'src/vueLib/models/settings';
import EnterNewPassword from 'src/vueLib/login/EnterNewPassword.vue';
import { defaultPermissions } from 'src/vueLib/checkboxes/permissions';
import SiteTitle from 'src/vueLib/general/SiteTitle.vue';

const { NotifyResponse } = useNotify();
const form = ref();
const localUser = ref<User>({
  user: '',
  email: '',
});

async function save() {
  if (!(await validateQForm(form.value))) {
    NotifyResponse(i18n.global.t('notAllRequiredFieldsFilled'), 'error');
    return;
  }

  localUser.value.role = { role: 'admin', permissions: defaultPermissions };
  localUser.value.role.permissions.forEach((p) => (p.permission = 31));
  localUser.value.settings = DefaultSettings();

  await appApi
    .post('users/add', JSON.stringify(localUser.value))
    .then(() => {
      window.location.reload();
    })
    .catch((err) => {
      NotifyResponse(err, 'error');
      return;
    });
}
</script>

<style>
.required .q-field__label::after {
  content: ' *';
  color: red;
}
</style>
