import { idlFactory as DataIdlFactory } from '../canisters/data/data.utils.did';
import { idlFactory as ManagerFactory } from '../canisters/manager/manager.utils.did';
import { idlFactory as StorageIdlFactory } from '../canisters/storage/storage.utils.did';
import { createActor } from './actor.utils';
import { fromNullable } from './did.utils';
export const createManagerActor = ({ identity }) => {
  return createActor({ canisterId: process.env.MANAGER_CANISTER_ID, idlFactory: ManagerFactory, identity });
};
export const getDataBucket = async ({ identity }) => {
  return getBucket({ identity, idlFactory: DataIdlFactory, initBucket: initDataBucket });
};
export const getStorageBucket = async ({ identity }) => {
  return getBucket({ identity, idlFactory: StorageIdlFactory, initBucket: initStorageBucket });
};
const getBucket = async ({ identity, idlFactory, initBucket }) => {
  if (!identity) {
    throw new Error('Invalid identity.');
  }
  const managerActor = await createManagerActor({ identity });
  const bucket = await initBucket({ managerActor });
  const bucketId = fromNullable(bucket.bucketId);
  const actor = bucketId ? await createBucketActor({ identity, bucketId, idlFactory }) : undefined;
  return {
    bucketId,
    actor
  };
};
const createBucketActor = ({ identity, bucketId, idlFactory }) => {
  return createActor({ canisterId: bucketId, idlFactory, identity });
};
const initDataBucket = async ({ managerActor }) => {
  const existingBucket = fromNullable(await managerActor.getData());
  if (!existingBucket) {
    return await managerActor.initData();
  }
  return existingBucket;
};
const initStorageBucket = async ({ managerActor }) => {
  const existingBucket = fromNullable(await managerActor.getStorage());
  if (!existingBucket) {
    return await managerActor.initStorage();
  }
  return existingBucket;
};
