import type { Recordable, UserInfo } from '@vben/types';

import { ref } from 'vue';
import { useRouter } from 'vue-router';

import { LOGIN_PATH } from '@vben/constants';
import { preferences } from '@vben/preferences';
import { resetAllStores, useAccessStore, useUserStore } from '@vben/stores';

import { notification } from 'antdv-next';
import { defineStore } from 'pinia';

import { getAccessCodesApi, getUserInfoApi, loginApi, logoutApi } from '#/api';
import { $t } from '#/locales';

export const useAuthStore = defineStore('auth', () => {
  const accessStore = useAccessStore();
  const userStore = useUserStore();
  const router = useRouter();

  const loginLoading = ref(false);

  function decodeRedirect(redirect?: string) {
    if (!redirect) return null;

    try {
      return decodeURIComponent(redirect);
    } catch {
      return redirect;
    }
  }

  function getRedirectQuery() {
    const routeRedirect = router.currentRoute.value.query?.redirect as
      | string
      | undefined;

    if (routeRedirect) return routeRedirect;

    // 兼容旧链接 /auth/login?redirect=... 在 hash 路由下被放到 location.search 的情况。
    const searchRedirect = new URLSearchParams(window.location.search).get(
      'redirect',
    );
    if (searchRedirect) return searchRedirect;

    // Web/Playground 生产配置会跳 /#/auth/login?redirect=...；
    // Admin 本地 history 模式下该 query 只存在于 location.hash。
    const hashQueryIndex = window.location.hash.indexOf('?');
    if (hashQueryIndex === -1) return null;

    return new URLSearchParams(
      window.location.hash.slice(hashQueryIndex + 1),
    ).get('redirect');
  }

  function buildExternalAuthRedirectUrl(target: string) {
    if (!accessStore.accessToken) return target;

    try {
      const url = new URL(target);
      url.searchParams.set('ktAccessToken', accessStore.accessToken);

      if (accessStore.accessCodes.length > 0) {
        url.searchParams.set(
          'ktAccessCodes',
          JSON.stringify(accessStore.accessCodes),
        );
      }

      if (userStore.userInfo) {
        url.searchParams.set('ktUserInfo', JSON.stringify(userStore.userInfo));
      }

      if (accessStore.wordpressAuth) {
        url.searchParams.set(
          'ktWordpressAuth',
          JSON.stringify(accessStore.wordpressAuth),
        );
      }

      return url.toString();
    } catch {
      return target;
    }
  }

  function redirectToExternalWithAuth(target: string) {
    window.location.href = buildExternalAuthRedirectUrl(target);
  }

  async function goToRedirect(fallbackPath: string) {
    const redirect = decodeRedirect(getRedirectQuery() || undefined);
    const target = redirect || fallbackPath;

    if (/^https?:\/\//i.test(target)) {
      redirectToExternalWithAuth(target);
      return;
    }

    await router.push(target);
  }

  /**
   * 异步处理登录操作
   * Asynchronously handle the login process
   * @param params 登录表单数据
   * @param onSuccess 成功之后的回调函数
   */
  async function authLogin(
    params: Recordable<any>,
    onSuccess?: () => Promise<void> | void,
  ) {
    // 异步处理用户登录操作并获取 accessToken
    let userInfo: null | UserInfo = null;
    try {
      loginLoading.value = true;
      const { accessToken, wordpressAuth } = await loginApi(params);

      // 如果成功获取到 accessToken
      if (accessToken) {
        accessStore.setAccessToken(accessToken);

        // 获取用户信息并存储到 accessStore 中
        const [fetchUserInfoResult, accessCodes] = await Promise.all([
          fetchUserInfo(),
          getAccessCodesApi(),
        ]);

        userInfo = fetchUserInfoResult;

        userStore.setUserInfo(userInfo);
        accessStore.setAccessCodes(accessCodes);
        accessStore.setWordpressAuth(wordpressAuth || null);

        if (accessStore.loginExpired) {
          accessStore.setLoginExpired(false);
        } else {
          onSuccess
            ? await onSuccess?.()
            : await goToRedirect(
                userInfo.homePath || preferences.app.defaultHomePath,
              );
        }

        if (userInfo?.realName) {
          notification.success({
            description: `${$t('authentication.loginSuccessDesc')}:${userInfo?.realName}`,
            duration: 3,
            title: $t('authentication.loginSuccess'),
          });
        }
      }
    } catch (error) {
      accessStore.setAccessToken(null);
      accessStore.setAccessCodes([]);
      accessStore.setWordpressAuth(null);
      userStore.setUserInfo(null);

      try {
        await logoutApi();
      } catch {
        // 不做任何处理
      }

      throw error;
    } finally {
      loginLoading.value = false;
    }

    return {
      userInfo,
    };
  }

  const isLoggingOut = ref(false); // 正在 logout 标识, 防止 /logout 死循环.

  async function logout(redirect: boolean = true) {
    if (isLoggingOut.value) return; // 正在登出中, 说明已进入循环, 直接返回.
    isLoggingOut.value = true; // 设置 标识

    try {
      await logoutApi();
    } catch {
      // 不做任何处理
    } finally {
      isLoggingOut.value = false; // 重置 标识

      resetAllStores();
      accessStore.setLoginExpired(false);
      accessStore.setWordpressAuth(null);
    }

    // 回登录页带上当前路由地址
    await router.replace({
      path: LOGIN_PATH,
      query: redirect
        ? {
            redirect: encodeURIComponent(router.currentRoute.value.fullPath),
          }
        : {},
    });
  }

  async function fetchUserInfo() {
    let userInfo: null | UserInfo = null;
    userInfo = await getUserInfoApi();
    userStore.setUserInfo(userInfo);
    return userInfo;
  }

  function $reset() {
    loginLoading.value = false;
  }

  return {
    $reset,
    authLogin,
    fetchUserInfo,
    loginLoading,
    logout,
    redirectToExternalWithAuth,
  };
});
