import { AuthClient } from '@dfinity/auth-client';
import { internetIdentityAuth } from '../../utils/identity.utils';
import { initUserWorker } from '../../workers/user.ic.worker';
import { deleteUser } from '../data/user.ic';
let authClient;
export const initAuth = async ({ success }) => {
  authClient = await AuthClient.create();
  const isAuthenticated = (await (authClient === null || authClient === void 0 ? void 0 : authClient.isAuthenticated())) || false;
  if (!isAuthenticated) {
    return;
  }
  const internetIdentity = await internetIdentityAuth();
  const user = await initUserWorker({ internetIdentity, host: `${window.location}` });
  await populateUser({ user, success });
};
const populateUser = async ({ user, success }) => {
  const { id, data } = user;
  const { name, email, photo_url } = data;
  const authUser = {
    uid: id,
    anonymous: false,
    gitHub: false,
    name,
    email,
    photo_url
  };
  await success({ authUser, user });
};
export const signOut = () => {
  return authClient === null || authClient === void 0 ? void 0 : authClient.logout();
};
export const signIn = async ({ onSuccess, onError }) => {
  authClient = authClient || (await AuthClient.create());
  await authClient.login(Object.assign({ onSuccess,
    onError }, (process.env.LOCAL_IDENTITY && {
    identityProvider: `http://localhost:8000?canisterId=${process.env.LOCAL_IDENTITY_CANISTER_ID}#authorize`
  })));
};
export const deleteAuth = ({ user }) => {
  return deleteUser(user.id);
};
export const getIdentity = () => {
  return authClient === null || authClient === void 0 ? void 0 : authClient.getIdentity();
};
