<template>
  <div class="flex items-center justify-center min-h-[70vh]">
    <el-card class="w-full max-w-md shadow-md">
      <div class="text-center space-y-3">
        <h1 class="text-xl font-bold text-gray-800">member.ose.tw</h1>
        <p class="text-sm text-gray-500">正在處理登入結果...</p>
        <el-alert
          v-if="error"
          :title="error"
          type="error"
          show-icon
          :closable="false"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { exchangeOidcCode } from '@/api/auth'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()
const error = ref('')

onMounted(async () => {
  const code = route.query.code
  const redirect = sessionStorage.getItem('post_login_redirect') || '/me'
  if (!code || typeof code !== 'string') {
    error.value = '缺少授權碼，請重新登入'
    return
  }

  try {
    const callbackUrl = `${window.location.origin}/auth/callback`
    const res = await exchangeOidcCode(code, callbackUrl)
    authStore.setToken(res.data.access_token)
    await authStore.fetchMe()
    sessionStorage.removeItem('post_login_redirect')
    router.replace(typeof redirect === 'string' ? redirect : '/me')
  } catch (err) {
    authStore.logout()
    const detail = err.response?.data?.detail
    if (detail === 'authentik_code_exchange_failed') {
      error.value = '授權碼交換失敗，請重新登入'
    } else {
      error.value = '登入失敗，請稍後再試'
    }
  }
})
</script>
