import { getConfig } from './helper';
import { Router } from './router';
import { LoginMethodType } from './types';
import { providerLogin } from './index';

const _CACHE_MAP = {};
export async function tryWecomLogin(location, fallback) {
  try {
    if (!_CACHE_MAP[location.href]) {
      _CACHE_MAP[location.href] = wecomLogin(location);
    }

    const res = await _CACHE_MAP[location.href];
    if (res) {
      _CACHE_MAP[location.href] = undefined;
      return;
    } else {
      fallback();
    }
  } catch (e) {
    console.error('企微原地登录失败，fallback to sso登录', e);
    fallback();
  }
}

async function wecomLogin(location) {
  const router = new Router(document.createElement('div'), location);
  const config = await getConfig(router);
  const loginMethods = config?.web || [];
  const loginTypes = [];
  const authList = [];
  let wecomConfig = undefined;
  loginMethods.forEach((item) => {
    if (!loginTypes.includes(item.type)) {
      loginTypes.push(item.type);
    }
    if (item.type === LoginMethodType.AUTH) {
      authList.push(item);
    }
    if (item.id === 'wecom') {
      wecomConfig = item;
    }
  });
  // if (loginTypes.length === 1 && authList.length === 1 && !config?.agreement?.enable) {
  if (wecomConfig) {
    await providerLogin(router, wecomConfig.id);
    return true;
  } else {
    return false;
  }
}
