import { toNullable, toTimestamp, fromNullable, fromUserSocial, fromTimestamp } from '../utils/did.utils';
import { initUserActor } from '../utils/user.utils';
import { initIdentity } from '../utils/identity.utils';
export const initUserWorker = async ({ internetIdentity: { delegationChain, identityKey }, host }) => {
  if (!delegationChain || !identityKey) {
    return;
  }
  const identity = initIdentity({ identityKey, delegationChain });
  const { userActor, ownerId } = await initUserActor({ identity, host });
  console.log('User IC about to GET');
  const t0 = performance.now();
  const user = await get({ userActor, ownerId });
  const t1 = performance.now();
  console.log('User IC GET done', t1 - t0, user);
  if (!user) {
    const newUser = await createUser({ userActor, ownerId });
    return convertUser({ user: newUser });
  }
  return convertUser({ user });
};
const createUser = async ({ userActor, ownerId }) => {
  const now = new Date();
  const newUser = {
    userId: ownerId,
    data: {
      name: toNullable(null),
      username: toNullable(null),
      bio: toNullable(null),
      photo_url: toNullable(null),
      email: toNullable(null),
      newsletter: [true],
      social: toNullable(null),
      created_at: toTimestamp(now),
      updated_at: toTimestamp(now)
    }
  };
  console.log('User IC about to SET');
  const t0 = performance.now();
  await userActor.set(newUser);
  const t1 = performance.now();
  console.log('User IC SET done', t1 - t0);
  return newUser;
};
const get = async ({ userActor, ownerId }) => {
  return fromNullable(await userActor.get(ownerId));
};
const convertUser = ({ user }) => {
  const { userId, data } = user;
  const { name, email, photo_url, newsletter, bio, social, created_at, updated_at, username } = data;
  return {
    id: userId.toText(),
    data: {
      anonymous: false,
      name: fromNullable(name),
      username: fromNullable(username),
      email: fromNullable(email),
      newsletter: fromNullable(newsletter),
      photo_url: fromNullable(photo_url),
      social: fromUserSocial(social),
      bio: fromNullable(bio),
      created_at: fromTimestamp(created_at),
      updated_at: fromTimestamp(updated_at)
    }
  };
};
