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 {
  devLoginApi,
  getAccessCodesApi,
  getUserInfoApi,
  loginApi,
  logoutApi,
} from '#/api';
import { $t } from '#/locales';
import {
  buildForcePasswordRoute,
  shouldForcePasswordChange,
} from '#/utils/password-reset';
import { clearAgentChatBrowserCache } from '#/utils/agent-chat-cache';

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,
    options: {
      notify?: boolean;
      onSuccess?: () => Promise<void> | void;
      skipRedirect?: boolean;
    } = {},
  ) {
    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 if (!options.skipRedirect) {
      const homePath =
        userInfo.homePath || preferences.app.defaultHomePath || '/';
      options.onSuccess
        ? await options.onSuccess()
        : await router.push(homePath);
    }

    if (options.notify !== false && 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 authDevLogin(account: string) {
    const { forceChangePassword, token: accessToken } = await devLoginApi({
      account,
    });
    if (!accessToken) {
      return {
        userInfo: null,
      };
    }
    return finalizeLogin(accessToken, forceChangePassword, {
      notify: false,
      skipRedirect: true,
    });
  }

  async function logout(redirect: boolean = true) {
    try {
      await logoutApi();
    } catch {
      // 不做任何处理
    }
    clearAgentChatBrowserCache(userStore.userInfo);
    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;
  }

  async function fetchAccessCodes() {
    const accessCodes = await getAccessCodesApi();
    accessStore.setAccessCodes(accessCodes);
    return accessCodes;
  }

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

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