<template>
  <div class="d-flex justify-content-center align-items-center min-vh-100">
    <div class="text-center">
      <div class="spinner-border text-primary mb-3" role="status"></div>
      <p class="text-muted">Synology 로그인 처리 중...</p>
    </div>
  </div>
</template>

<script setup lang="ts">
definePageMeta({ layout: false })

const router = useRouter()

onMounted(async () => {
  // hash fragment에서 access_token 추출
  const hash = window.location.hash.substring(1)
  const params = new URLSearchParams(hash)
  const accessToken = params.get('access_token')
  const state = params.get('state')
  const error = params.get('error')
  
  if (error) {
    router.push(`/login?error=${encodeURIComponent('Synology 인증이 취소되었습니다.')}`)
    return
  }
  
  if (!accessToken) {
    router.push(`/login?error=${encodeURIComponent('인증 토큰이 없습니다.')}`)
    return
  }
  
  try {
    // 서버로 access_token 전송하여 로그인 처리
    await $fetch('/api/auth/synology/verify', {
      method: 'POST',
      body: { accessToken, state }
    })
    router.push('/')
  } catch (e: any) {
    router.push(`/login?error=${encodeURIComponent(e.data?.message || 'Synology 로그인에 실패했습니다.')}`)
  }
})
</script>
