<template>
  <div class="d-flex justify-center align-center text-center" style="height: 100vh;">
    <div>
      <v-progress-circular indeterminate color="primary" size="64"></v-progress-circular>
      <p class="mt-4 text-h6">Verifying your session...</p>
      <v-alert v-if="errorMessage" type="error" class="mt-4">
        {{ errorMessage }}
      </v-alert>
    </div>
    <shared-app-snackbar />
  </div>
</template>

<script setup lang="ts">
definePageMeta({
  layout: "blank"
});
import { ref, onMounted } from 'vue';
import { useSnackbarStore } from '~/store/snackbar';

const snackbarStore = useSnackbarStore();
const errorMessage = ref('');

onMounted(async () => {
  const urlParams = new URLSearchParams(window.location.search);
  const accessToken = urlParams.get('access_token');
  const refreshToken = urlParams.get('refresh_token');

  if (!accessToken || !refreshToken) {
    // errorMessage.value = 'Access token or refresh token is missing from the URL.';
    snackbarStore.showSnackbar('Verification failed: Missing tokens.', 'error');
    // Optionally redirect to login after a delay
    setTimeout(() => {
      window.location.href = '/auth/login';
    }, 3000);
    return;
  }

  try {
    await $fetch('/api/auth/sessionUserStore', {
      method: 'POST',
      body: {
        accessToken,
        refreshToken,
      },
    });

    localStorage.setItem('accessToken', accessToken);
    localStorage.setItem('refreshToken', refreshToken);

    // Redirect to dashboard on success
    window.location.href = '/apps/dashboard';
  } catch (error: any) {
    const verificationError = error?.data?.message || error?.message || 'An error occurred during verification.';
    // errorMessage.value = verificationError;
    snackbarStore.showSnackbar(verificationError, 'error');
    // Optionally redirect to login after a delay
    setTimeout(() => {
      window.location.href = '/auth/login';
    }, 3000);
  }
});
</script>

<style scoped>
/* You can add custom styles here if needed */
</style>