import { nanoid } from 'nanoid';
import { getData, setData } from '../utils/data.utils';
import { initIdentity } from '../utils/identity.utils';
import { getDataBucket } from '../utils/manager.utils';
export const initUserWorker = ({ internetIdentity }, onInitUserSuccess, log) => initUser({ internetIdentity }, onInitUserSuccess, log);
const initUser = async ({ internetIdentity: { delegationChain, identityKey } }, onInitUserSuccess, log) => new Promise(async (resolve) => {
  if (!delegationChain || !identityKey) {
    resolve();
    return;
  }
  const identity = initIdentity({ identityKey, delegationChain });
  const { actor } = await getDataBucket({ identity });
  if (!actor) {
    setTimeout(async () => {
      await initUser({ internetIdentity: { delegationChain, identityKey } }, onInitUserSuccess, log);
      resolve();
    }, 2000);
    return;
  }
  const user = await initUserData({ actor, log });
  await onInitUserSuccess(user);
  resolve();
});
const initUserData = async ({ actor, log }) => {
  log({ msg: `[get][start] user` });
  const t0 = performance.now();
  const user = await getData({ key: `/user`, actor });
  const t1 = performance.now();
  log({ msg: `[get][done] user`, duration: t1 - t0 });
  if (!user) {
    const newUser = await createUser({ actor, log });
    return newUser;
  }
  return user;
};
const createUser = async ({ actor, log }) => {
  const now = new Date();
  const id = nanoid();
  const data = {
    created_at: now,
    updated_at: now
  };
  const user = await setData({ key: `/user`, id, data, actor, log });
  return user;
};
