<script setup>
import { useRoute, useRouter } from 'vue-router';
import { onMounted } from 'vue';
import { useStore } from 'vuex';
import { isAdmin } from "@/global/request";
import { redirectToSSO } from '@/utils/sso';
import axios from 'axios';

const ASSET_URL = import.meta.env.VITE_ASSET_URL
const route = useRoute();
const router = useRouter();
const store = useStore();

onMounted(async () => {
  const query = new URLSearchParams(window.location.search);
  const error = query.get('error');

  if (error === 'token_exchange_failed') {
    // 顯示錯誤通知
    alert('SSO 登入失敗，請稍後再試');
    redirectToSSO();
    return;
  }

  const ssoToken = route.query.sso_token;
  const apiToken = route.query.api_token;

  if (ssoToken && apiToken) {
    try {
      // 呼叫你系統的 /api/user 拿 user profile
      const { data: user } = await axios.get(`${ASSET_URL}/api/getUser`, {
        headers: {
          Authorization: `Bearer ${apiToken}`
        }
      });

      // 儲存使用者資料
      localStorage.setItem('access_token', ssoToken);
      localStorage.setItem("user", JSON.stringify(user));
      localStorage.setItem("APP_USER_TOKEN", apiToken);

      store.commit("auth/SET_USER", user);
      store.commit("auth/SET_AUTHENTICATED", true);

      // 根據權限導向
      if (isAdmin()) {
        window.location.href = `${ASSET_URL}/home/adminHome`;
      } else {
        window.location.href = `${ASSET_URL}/home/parentHome`;
      }
    } catch (err) {
      console.error("取得使用者資料失敗", err);
      alert('登入驗證失敗，請重新登入');
      redirectToSSO();
    }
  } else {
    router.replace('/error'); // 缺少 token 則跳錯誤
  }
});
</script>

<template>
  <div>登入中，請稍候...</div>
</template>
