<template>
  <NuxtLayout name="blank">
    <v-app>
      <div class="d-flex flex-column align-center justify-center fill-height">
        <v-progress-circular indeterminate size="64" />
        <span class="mt-3">{{ $t('please_wait') }}</span>
      </div>
    </v-app>
  </NuxtLayout>
</template>

<script setup lang="ts">
/**
 * Disable the default layout, the page will use the layout defined with <NuxtLayout />
 * @see https://nuxt.com/docs/guide/directory-structure/layouts#overriding-a-layout-on-a-per-page-basis
 */
import type { RouteLocationNormalizedLoaded } from 'vue-router'
import { useEntityManager } from '~/composables/data/useEntityManager'
import ConnectionRequest from '~/models/ApiResources/HelloAsso/ConnectionRequest'
import { useOrganizationProfileStore } from '~/stores/organizationProfile'

definePageMeta({
  name: 'helloasso_callback_page',
  layout: false,
})

const organizationProfile = useOrganizationProfileStore()

const { em } = useEntityManager()

const route: RouteLocationNormalizedLoaded = useRoute()

if (!route.query.code) {
  throw new Error('Missing parameter')
}

const authorizationCode: Ref<string> = ref(route.query.code as string)

const connectionRequest: ConnectionRequest = em.newInstance(
  ConnectionRequest,
  {
    organizationId: organizationProfile.id,
    authorizationCode: authorizationCode.value,
  },
)

onMounted(async () => {
  await em.persist(connectionRequest)
  console.log('Connection request created')

  // Send a event to the parent window to notify the connection request has been created (in case SSE is not available)
  window.opener?.postMessage(
    { code: authorizationCode.value },
    window.location.origin,
  )

  // Close the popup
  window.close()
})

</script>

<style scoped lang="scss"></style>
