import type { Router } from 'vue-router';

import { ElMessage } from 'element-plus';

import { $t } from '#/locales';

const FORCE_PASSWORD_NOTICE_INTERVAL = 1500;
const PROFILE_PATH = '/profile';

let lastForcePasswordNoticeAt = 0;

export function buildForcePasswordRoute() {
  return {
    path: PROFILE_PATH,
    query: {
      force: '1',
      tab: 'password',
    },
  };
}

export function isForcePasswordRoute(
  route: Pick<{ path?: string; query?: Record<string, any> }, 'path' | 'query'>,
) {
  return route.path === PROFILE_PATH && route.query?.tab === 'password';
}

export function shouldForcePasswordChange(
  userInfo?: null | Record<string, any>,
  forceChangePassword?: boolean,
) {
  return !!forceChangePassword || isPasswordResetRequired(userInfo);
}

export function isPasswordResetRequired(userInfo?: null | Record<string, any>) {
  return !!userInfo?.passwordResetRequired;
}

export function resolveForcePasswordPath(router: Router) {
  return router.resolve(buildForcePasswordRoute()).fullPath;
}

export function notifyForcePasswordChange() {
  const now = Date.now();
  if (now - lastForcePasswordNoticeAt < FORCE_PASSWORD_NOTICE_INTERVAL) {
    return;
  }
  lastForcePasswordNoticeAt = now;
  ElMessage({
    message: $t('sysAccount.forceChangePasswordNavigateTip'),
    type: 'warning',
    duration: 2200,
    grouping: true,
    plain: true,
    showClose: true,
  });
}
