<script setup lang="ts">
import type { Database } from '~/types/supabase'
const user = useSupabaseUser()
const client = useSupabaseClient<Database>()
const redirectInfo = useSupabaseCookieRedirect()

watch(user, async (newUser) => {
  if (newUser) {
    console.log('Logged-in user: ', newUser)

    // Update profile with Discord username and avatar
    const { error } = await client.from('profiles')
    .upsert({
      id: newUser.id,
      discord_username: newUser.user_metadata?.full_name || 'Unknown',
      avatar_url: newUser.user_metadata?.avatar_url || '',
      discord_id: newUser.user_metadata?.provider_id || '',
    })
    .eq('id', newUser.id)

    if (error) {
      console.error('Error updating profile with Discord info:', error)
    }
    else {
      console.log('Profile updated with Discord username and avatar')
    }
  }

  if (user.value) {
    // Get redirect path, and clear it from the cookie
    let path = redirectInfo.pluck()

    // Redirect to the saved path, or fallback to home
    if (path?.includes('login')) path = '/'
    return navigateTo(path || '/') 
  }}, 
  { immediate: true }
)
</script>

<template>
  <div>Waiting for login...</div>
</template>
