<script setup lang="ts">
import { z } from 'zod'

const loginSchema = z.object({
  name: z.string().min(3, 'Please enter a valid username'),
  password: z.string().min(3, 'Password must be at least 3 characters'),
})

const { login } = useUserStore()

type LoginFormData = z.infer<typeof loginSchema>

const isLoading = ref(false)
const apiErrors = ref<Record<string, string>>({})

async function onSubmit(data: LoginFormData) {
  isLoading.value = true

  const result = await xfetch('/api/v1/authentication/login', 'POST', {
    name: data.name,
    password: data.password,
  })

  if (result.success) {
    const { data: rawdata, meta } = result.body
    if (meta.status === 'verified') {
      await login(rawdata)
      await navigateTo('/')
    }
  } else {
    if (result.errors) {
      Object.entries(result.errors).forEach(
        ([field, errorInfo]: [string, any]) => (apiErrors.value[field] = errorInfo.message),
      )
    } else {
      apiErrors.value.general = result.error?.message || result.message || 'Login failed'
    }
  }

  isLoading.value = false
}
</script>

<template>
  <AppAuthLogin :schema="loginSchema" :is-loading="isLoading" @submit="onSubmit" />
</template>

<style scoped></style>
