import { useCreation } from 'ahooks';
import { useStateContext } from '../contexts/state';
import useSecurity from './security';
import { getVisitorId } from '../../utils';

export default function useAuthUrl({ disableSwitchApp, tokenState }) {
  const { appInfoList, connectState } = useStateContext();
  const { encryptKey } = useSecurity();
  const urlWithParams = useCreation(() => {
    if (!tokenState.url) {
      return '';
    }
    const canSwitch = !disableSwitchApp && appInfoList.length > 1;
    const resultUrl = new URL(tokenState.url || 'https://www.didwallet.io');
    const actionRawUrl = resultUrl.searchParams.get('url');
    if (actionRawUrl && canSwitch) {
      const actionUrl = new URL(decodeURIComponent(actionRawUrl));
      actionUrl.searchParams.set('_ek_', encryptKey);
      const visitorId = getVisitorId();
      if (visitorId) {
        actionUrl.searchParams.set('vid', visitorId);
      }
      if (connectState?.sourceAppPid) {
        actionUrl.searchParams.set('spid', connectState?.sourceAppPid);
      }
      resultUrl.searchParams.set('url', actionUrl.toString());
    }
    return resultUrl.toString();
  }, [tokenState.url, appInfoList.length, connectState?.sourceAppPid, encryptKey]);
  return urlWithParams;
}
