createContactsWithPatient method

Implementation

Future<List<DecryptedContactDto>?> createContactsWithPatient(
    UserDto user, DecryptedPatientDto patient, List<DecryptedContactDto> contacts, CryptoConfig<DecryptedContactDto, ContactDto> config) async {
  var delegations = <String>{...(user.autoDelegations["all"] ?? {}), ...(user.autoDelegations["medicalInformation"] ?? {})};
  final secret = (await config.crypto.decryptEncryptionKeys(user.dataOwnerId()!, patient.delegations)).firstOrNull;
  if (secret == null) {
    throw FormatException("Cannot get delegation key for ${patient.id} and hcp ${user.dataOwnerId()}");
  }
  var newContacts = await this.rawCreateContacts(await Future.wait(contacts.map((contact) async {
    var encContact = await config.encryptContact(user.dataOwnerId()!, delegations, await contact.initDelegations(user, config));

    final secretForDelegates = await Future.wait((<String>{...delegations, user.dataOwnerId()!})
        .map((String d) async => Tuple2(d, await config.crypto.encryptValueForHcp(user.dataOwnerId()!, d, contact.id, patient.id))));

    encContact.cryptedForeignKeys = {
      ...encContact.cryptedForeignKeys,
      ...Map.fromEntries(secretForDelegates
          .map((t) => MapEntry(t.item1, <DelegationDto>{DelegationDto(owner: user.dataOwnerId()!, delegatedTo: t.item1, key: t.item2.item1)})))
    };
    encContact.secretForeignKeys = <String>{secret};

    return encContact;
  })));
  return newContacts == null
      ? null
      : await Future.wait(newContacts.map((newContact) => config.decryptContact(user.dataOwnerId()!, newContact)));
}