<script setup lang="ts">
import { onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { apiErrorMessage } from '../api/http'
import { useAuthStore } from '../stores/auth'

const route = useRoute()
const router = useRouter()
const auth = useAuthStore()

function safeRedirect(value: unknown) {
  const path = String(value ?? '')
  return path.startsWith('/') && !path.startsWith('//') ? path : '/dashboard'
}

onMounted(async () => {
  const code = String(route.query.code ?? '')
  if (!code) {
    await router.replace({ name: 'login', query: { ssoError: 'authentication_failed' } })
    return
  }

  try {
    await auth.exchangeSso(code)
    await router.replace(safeRedirect(route.query.redirect))
  } catch (error) {
    ElMessage.error(apiErrorMessage(error))
    await router.replace({ name: 'login', query: { ssoError: 'authentication_failed' } })
  }
})
</script>

<template>
  <main class="sso-callback-page">
    <el-icon class="is-loading" :size="34"><Loading /></el-icon>
    <h1>正在完成统一身份认证</h1>
    <p>请稍候，不要关闭此页面。</p>
  </main>
</template>
