class AcceptApplicationInviteServiceImpl extends InviteService<ApplicationInvite> implements AcceptApplicationInviteService {

    @Override
    @Transactional
    public ServiceResult<Void> acceptInvite(String inviteHash, long userId, Optional<Long> organisationId) {
        return find(invite(inviteHash), user(userId)).andOnSuccess((invite, user) -> {
            if (!invite.getEmail().equalsIgnoreCase(user.getEmail())) {
                LOG.error(
                        "Invite (id: {}) email address does not match user's (id: {})",
                        invite.getId(),
                        user.getId()
                );

                return serviceFailure(new Error(
                        "Invite email address not the same as the user's email address",
                        NOT_ACCEPTABLE
                ));
            }

            invite.open();

            if (invite.getInviteOrganisation().getOrganisation() == null) {
                if (!organisationId.isPresent()) {
                    return serviceFailure(notFoundError(Organisation.class));
                }
                assignOrganisationToInvite(invite, organisationRepository.findById(organisationId.get()).orElse(null));
            }

            initializeInvitee(invite, user);

            return serviceSuccess();
        });
    }

}