<template>
  <UniqueTextField
    ref="uniqueTextField"
    v-model="userEmail"
    label="Email"
    :check-availability="checkEmailAvailability"
    unique-validation-message="User email must be unique"
    is-unique-message="User email is available"
    is-not-unique-message="User email is already taken"
  />
</template>

<script setup lang="ts">
import { ref } from "vue"

import usersApi from "@/api/users-api"

import UniqueTextField from "@/components/common/UniqueTextField.vue"

const userEmail = defineModel<string | null | undefined>({
  required: true,
})

async function checkEmailAvailability(email: string) {
  const { users } = await usersApi.list({
    where: {
      email,
    },
  })
  return users.length === 0
}

const uniqueTextField = ref<InstanceType<typeof UniqueTextField> | null>(null)
</script>
