<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useKeycloak } from "~/composables/useKeycloack"

const error = ref<string | null>(null)
const { initKeycloak, isAuthenticated, getResponse, loginSSO } = useKeycloak()
const profile = ref<any>(null)
const token = ref<string | null>(null);

onMounted(async () => {
  try {
    // Initialize Keycloak with login-required to ensure tokens set (Keycloak will process the code/state returned)
    await initKeycloak('login-required')
    // small delay to allow token propagation
    if (isAuthenticated.value) {
      await getResponse()
    } else {
      await loginSSO({ redirectUri: '/auth/sso' })
    }
  } catch (err: any) {
    error.value = err?.message || String(err)
  }
})
</script>

<template>
  <div style="max-width:720px;margin:40px auto">
    <h2>Processing login...</h2>
    <p v-if="error">Terjadi error: {{ error }}</p>
    <p v-else>Mohon tunggu, sedang memproses otentikasi dan mengarahkan Anda ...</p>
  </div>
</template>
