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

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

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

import { ElNotification } from 'element-plus';
import { defineStore } from 'pinia';

import { getAccessCodesApi, getUserInfoApi, loginApi, logoutApi } from '#/api';
import { $t } from '#/locales';
import {
  buildForcePasswordRoute,
  shouldForcePasswordChange,
} from '#/utils/password-reset';

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

  const loginLoading = ref(false);

  async function finalizeLogin(
    accessToken: string,
    forceChangePassword?: boolean,
    onSuccess?: () => Promise<void> | void,
  ) {
    let userInfo: null | UserInfo = null;
    accessStore.setAccessToken(accessToken);

    const [fetchUserInfoResult, accessCodes] = await Promise.all([
      fetchUserInfo(),
      getAccessCodesApi(),
    ]);

    userInfo = fetchUserInfoResult;
    userStore.setUserInfo(userInfo);
    accessStore.setAccessCodes(accessCodes);

    const forcePasswordChange = shouldForcePasswordChange(
      userInfo,
      forceChangePassword,
    );

    if (accessStore.loginExpired) {
      accessStore.setLoginExpired(false);
    }

    if (forcePasswordChange) {
      await router.push(buildForcePasswordRoute());
    } else {
      onSuccess
        ? await onSuccess?.()
        : await router.push(
            userInfo.homePath || preferences.app.defaultHomePath,
          );
    }

    if (userInfo?.nickname) {
      ElNotification({
        message: `${$t('authentication.loginSuccessDesc')}:${userInfo?.nickname}`,
        title: $t('authentication.loginSuccess'),
        type: 'success',
      });
    }

    return {
      userInfo,
    };
  }

  /**
   * 异步处理登录操作
   * Asynchronously handle the login process
   * @param params 登录表单数据
   */
  async function authLogin(
    params: Recordable<any>,
    onSuccess?: () => Promise<void> | void,
  ) {
    try {
      loginLoading.value = true;
      const { forceChangePassword, token: accessToken } = await loginApi(params);

      if (accessToken) {
        return await finalizeLogin(accessToken, forceChangePassword, onSuccess);
      }
    } finally {
      loginLoading.value = false;
    }

    return {
      userInfo: null,
    };
  }

  async function logout(redirect: boolean = true) {
    try {
      await logoutApi();
    } catch {
      // 不做任何处理
    }
    resetAllStores();
    accessStore.setLoginExpired(false);

    // 回登录页带上当前路由地址
    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,
  };
});
