<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'

import { verifyEmail } from '@/services/api'
import { ApiError } from '@/services/http'
import { useAuthStore } from '@/stores/auth'

const route = useRoute()
const token = computed(() => (typeof route.query.token === 'string' ? route.query.token : ''))

const loading = ref(true)
const message = ref<string>('')
const error = ref<string | null>(null)

const auth = useAuthStore()

onMounted(async () => {
  if (!token.value) {
    loading.value = false
    error.value = '缺少 token'
    return
  }

  try {
    const resp = await verifyEmail(token.value)
    message.value = resp.message
    if (resp.session_invalidated) {
      auth.logout()
    } else {
      auth.markEmailVerified()
    }
  } catch (err) {
    if (err instanceof ApiError) {
      error.value = `[${err.code}] ${err.message}`
    } else {
      error.value = '验证失败，请稍后再试'
    }
  } finally {
    loading.value = false
  }
})
</script>

<template>
  <div class="mx-auto max-w-md">
    <div class="rounded-xl border border-slate-200 bg-white p-6">
      <h1 class="text-xl font-semibold text-slate-900">验证邮箱</h1>

      <div v-if="loading" class="mt-4 text-sm text-slate-600">处理中…</div>
      <div v-else-if="error" class="mt-4 rounded-lg border border-rose-200 bg-rose-50 p-3 text-sm text-rose-900">
        {{ error }}
      </div>
      <div v-else class="mt-4 rounded-lg border border-emerald-200 bg-emerald-50 p-3 text-sm text-emerald-900">
        {{ message || '邮箱验证成功' }}
      </div>

      <div class="mt-5 text-sm text-slate-600">
        <router-link to="/login" class="text-indigo-600 hover:text-indigo-700">去登录</router-link>
        或
        <router-link to="/" class="text-indigo-600 hover:text-indigo-700">返回首页</router-link>
      </div>
    </div>
  </div>
</template>
