<template>
  <v-app>
    <v-main>
      <v-container class="fill-height" fluid>
        <v-row align="center" justify="center" class="fill-height">
          <v-col cols="12" class="text-center">
            <v-progress-circular 
              :size="70" 
              :width="7" 
              color="primary" 
              indeterminate
            ></v-progress-circular>
            <h3 class="mt-4">Processing authentication...</h3>
            <p class="text-body-2 mt-2">Please wait while we complete your login</p>
          </v-col>
        </v-row>
      </v-container>
    </v-main>
  </v-app>
</template>

<script setup lang="ts">
// Define page meta for public access (no auth required)
definePageMeta({
  auth: false,
  layout: false
});

// Handle OAuth callback
onMounted(async () => {
  try {
    const route = useRoute()
    const keycloak = useKeycloak()
    
    // Check if we have an authorization code
    const code = route.query.code as string
    const state = route.query.state as string
    const error = route.query.error as string
    
    if (error) {
      console.error('OAuth error:', error, route.query.error_description)
      throw new Error(`Authentication failed: ${error}`)
    }
    
    if (!code) {
      throw new Error('No authorization code received')
    }
    
    console.log('[CALLBACK] Processing OAuth callback with code:', code.substring(0, 10) + '...')
    
    // Initialize Keycloak if not already done
    if (!keycloak.isInitialized.value) {
      await keycloak.initKeycloak()
    }
    
    // Check if user is now authenticated
    if (keycloak.isAuthenticated.value) {
      console.log('[CALLBACK] User authenticated successfully')
      // Redirect to dashboard
      await navigateTo('/dashboard')
    } else {
      throw new Error('Authentication process failed')
    }
    
  } catch (error) {
    console.error('[CALLBACK] Authentication error:', error)
    
    // Show error and redirect to login
    const toast = useToast()
    toast.error('Authentication failed. Unable to complete login. Please try again.')
    
    await navigateTo('/login')
  }
})

useHead({
  title: 'Authenticating...'
})
</script>
