<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { RouterLink, useRoute } from 'vue-router'
import { getApiErrorMessage } from '@/services/api'
import { authService } from '@/modules/auth/services/authService'
import { useAuthStore } from '@/stores/auth'

const route = useRoute()
const auth = useAuthStore()
const message = ref('')
const error = ref('')
const loading = ref(false)

async function verify() {
  const verificationUrl = String(route.query.verification_url || '')

  if (!verificationUrl) {
    error.value = 'Verification link is missing required information.'
    return
  }

  loading.value = true
  error.value = ''
  message.value = ''

  try {
    const response = await authService.verifyEmail(verificationUrl)
    message.value = response.message

    if (response.data?.user) {
      auth.setUser(response.data.user)
    }
  } catch (verifyError) {
    error.value = getApiErrorMessage(verifyError, 'Unable to verify email address.')
  } finally {
    loading.value = false
  }
}

onMounted(verify)
</script>

<template>
  <section class="panel form-page">
    <h2>Email Verification</h2>
    <p>Confirming your BizNovia account email.</p>

    <p v-if="loading" class="muted">Verifying email...</p>
    <p v-if="message" class="success">{{ message }}</p>
    <p v-if="error" class="error">{{ error }}</p>

    <RouterLink v-if="message" class="button primary" to="/">Go to Dashboard</RouterLink>
    <RouterLink v-else class="button ghost" to="/login">Back to Login</RouterLink>
  </section>
</template>
