<template>
  <div>
    <p>User Profil: </p>
    <pre>{{ tokenUser }}</pre>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';

const tokenUser = useCookie('user_token_profile');
const runtimeconfig = useRuntimeConfig();


const sessionState = ref('');
const issuer = ref('');
const code = ref('');
onMounted(async () => {
  const url = window.location.href;
  const urlParams = new URL(url).searchParams;

  // Ambil parameter yang diperlukan
  sessionState.value = urlParams.get('session_state') || '';
  issuer.value = urlParams.get('iss') || '';
  code.value = urlParams.get('code') || '';

  if (code.value) {
    try {
      const tokenUrl = `${issuer.value}/protocol/openid-connect/token`;
      const response = await $fetch(tokenUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams({
          grant_type: 'authorization_code',
          client_id: runtimeconfig.public.keycloakClient, // Ganti dengan client ID Anda
          client_secret: runtimeconfig.public.keycloakSecretKey, // Ganti dengan client secret Anda
          code: urlParams.get('code'),
          redirect_uri: `${runtimeconfig.public.keycloakRedirectURI}/callback`, // Ganti dengan redirect URI Anda
        }),
      });
      const accessToken = response.access_token;
      tokenUser.value = accessToken;
      // Ambil informasi pengguna
      const userInfoUrl = `${issuer.value}/protocol/openid-connect/userinfo`;
      const userInfoResponse = await $fetch(userInfoUrl, {
        headers: {
          Authorization: `Bearer ${accessToken}`,
        },
      });
      tokenUser.value = JSON.stringify(userInfoResponse);
    } catch (error) {
      console.error('Error during token exchange or user info fetch:', error);
    }
  }
});

</script>

<style></style>