<template>
  <breadcrumb v-if="false" :title="$t('Processing authentication...')" center />
</template>

<script lang="ts" setup>
import {useUserStore} from "@/pinia/useUserStore";
import type {ISocialCallback} from "@/types/social-callback-d-t";
import {convertUserLoginResponse} from "@/plugins/data/user-login-data";
import formDataService from "@/services/formDataService";
import type {AxiosResponse} from "axios";

const userStore = useUserStore();
const route = useRoute();
const loading = useLoading();
const provider = route.params.provider as string;
const code = route.query.code as string;
const redirectTo = ref("/login");

onMounted(() => {
  $axios
      .post(`/auth/${provider}`, formDataService({code}))
      .then((response: AxiosResponse<ISocialCallback>) => {
        // console.log(23, response?.data)
        const res: ISocialCallback = response?.data;
        if (res?.data) {
          res.data = convertUserLoginResponse(res.data);
        }
        // console.log(28, res)

        if (res?.status === 'success') {
          if (res?.data) {
            userStore.setUser(res?.data);
          }

          redirectTo.value = '/';
        } else {
          console.error('38: Authentication error:', res?.message)
        }

        return res
      })
      .catch(error => {
        console.error('50: Authentication error:', error)

        return error
      })
      .finally(() => {
        if (process.client) {
          nextTick(() => {
            window.location.href = redirectTo.value;

            setTimeout(() => {
              loading.stop();
            }, 2000);
          });
        }
      });
})
</script>