<script setup>
// Get the token from the URL (/callback/microsoft/token#code=1234&client_info=1234&state=1234&session_state=1234)
import { useRoute } from 'vue-router';
import {onMounted, ref, watch} from 'vue';
import { SessionUser } from "@/components/session/token/SessionUser.vue";

// Error handling
const status = ref({
  complete: false, // Indicates if the token has been received, and been sent to the server
  success: false,
  error: false,
  message: ''
});

// Get the token from the URL
const route = useRoute();
const code = ref(null);
const client_info = ref(null);
const state = ref(null);
const session_state = ref(null);

const sendToken = async () => {
  // Send the token to the server
  await SessionUser.request(
      '/callback/microsoft/token',
      'POST',
      {
        code: code.value,
        client_info: client_info.value,
        state: state.value,
        session_state: session_state.value
      }
  ).then((response) => {
    console.log('Successfully stored token', response);
    status.value.success = true;
    status.value.message = 'Token stored successfully';
    status.value.complete = true;
  }).catch((error) => {
    console.error('Error storing token', error);
    status.value.error = true;
    status.value.message = 'Error storing token';
    status.value.complete = true;
  });
};

const getToken = () => {
  const url = route.fullPath;
  const params = new URLSearchParams(url.split('#')[1]);
  code.value = params.get('code');
  client_info.value = params.get('client_info');
  state.value = params.get('state');
  session_state.value = params.get('session_state');
  // Verify the token
  if (code.value && client_info.value && state.value && session_state.value) {
    status.value.message = 'Token received successfully';
    sendToken();
  } else {
    status.value.error = true;
    status.value.message = 'Error receiving token';
    status.value.complete = true;
  }
};

onMounted(() => {
  getToken();
  console.log(code.value);
  console.log(client_info.value);
  console.log(state.value);
  console.log(session_state.value);
});
</script>

<template>
  <template v-if="status.complete">
    <div v-if="status.success" class="notification is-success">
      <p>{{ status.message }}</p>
    </div>
    <div v-if="status.error" class="notification is-danger">
      <p>{{ status.message }}</p>
    </div>
  </template>
  <div class="container">
    <h1>Microsoft Callback Token</h1>
    <p>Code: {{ code }}</p>
    <p>Client Info: {{ client_info }}</p>
    <p>State: {{ state }}</p>
    <p>Session State: {{ session_state }}</p>
    <div v-if="status.success" class="notification is-success">
      <p>{{ status.message }}</p>
    </div>
    <div v-if="status.error" class="notification is-danger">
      <p>{{ status.message }}</p>
    </div>
  </div>
</template>

<style scoped>

</style>