<script setup>
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

import { socialCallback } from '../api/auth'
import { bindSocial } from '../api/settings'

const router = useRouter()
const statusText = ref('正在完成绑定')
const pendingSettingsBindKey = 'zsglpt_social_settings_bind_token'

onMounted(async () => {
  const params = new URLSearchParams(window.location.search || '')
  const provider = String(params.get('provider') || params.get('type') || '').trim()
  const code = String(params.get('code') || '').trim()
  if (!provider || !code) {
    ElMessage.error('快捷登录回调参数不完整')
    router.replace('/app/accounts')
    return
  }

  try {
    const data = await socialCallback({ provider, code, mode: 'bind' })
    if (data?.success && data?.bound) {
      ElMessage.success('快捷登录已绑定')
      router.replace('/app/accounts')
      return
    }
    if (!data?.bind_token) {
      ElMessage.warning('未获取到绑定凭证')
      router.replace('/app/accounts')
      return
    }
    try {
      await bindSocial({ bind_token: data.bind_token })
      ElMessage.success('快捷登录已绑定')
    } catch (error) {
      if (error?.response?.status === 401) {
        window.sessionStorage.setItem(pendingSettingsBindKey, data.bind_token)
        ElMessage.info('请先登录后完成绑定')
        router.replace('/login')
        return
      }
      throw error
    }
    router.replace('/app/accounts')
  } catch (error) {
    const payload = error?.response?.data
    statusText.value = payload?.error || '快捷登录绑定失败'
    ElMessage.error(statusText.value)
    router.replace('/app/accounts')
  }
})
</script>

<template>
  <div class="callback-wrap">
    <el-card shadow="never" class="callback-card">
      <el-skeleton :rows="3" animated />
      <div class="callback-text">{{ statusText }}</div>
    </el-card>
  </div>
</template>

<style scoped>
.callback-wrap {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.callback-card {
  width: min(420px, 94vw);
  border-radius: var(--app-radius);
  border: 1px solid var(--app-border);
}

.callback-text {
  margin-top: 12px;
  color: var(--app-muted);
  font-size: 13px;
  text-align: center;
}
</style>
