import { log } from '@deckdeckgo/editor';
import { AuthClient } from '@dfinity/auth-client';
import { internetIdentityAuth } from '../../utils/identity.utils';
import { createManagerActor } from '../../utils/manager.utils';
import { initUserWorker } from '../../workers/user.ic.worker';
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();
  await initUser({ success });
  const onInitUserSuccess = async (user) => await authenticatedUser({ user, success });
  await initUserWorker({ internetIdentity }, onInitUserSuccess, log);
};
// If first sign-in, initializing the canister can take a while therefore we already emit a not fully authenticated user
const initUser = async ({ success }) => {
  const authUser = {
    state: 'initialization'
  };
  await success({ authUser, user: undefined });
};
const authenticatedUser = async ({ user, success }) => {
  const { id, data } = user;
  const { name, email, photo_url } = data;
  const authUser = {
    uid: id,
    state: 'authenticated',
    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 = async (_auth) => {
  const identity = getIdentity();
  if (!identity) {
    throw new Error('Invalid identity.');
  }
  const managerActor = await createManagerActor({ identity });
  await Promise.all([managerActor.delData(), managerActor.delStorage()]);
};
export const getIdentity = () => {
  return authClient === null || authClient === void 0 ? void 0 : authClient.getIdentity();
};
