"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.forgetWebId = exports.finishInteraction = exports.ACCOUNT_PROMPT = exports.assertOidcInteraction = void 0;
const LogUtil_1 = require("../../logging/LogUtil");
const BadRequestHttpError_1 = require("../../util/errors/BadRequestHttpError");
const logger = (0, LogUtil_1.getLoggerFor)('AccountUtil');
/**
 * Asserts `oidcInteraction` is defined, throws the correct error in case this is not the case.
 * The error contains the relevant error code that can be used to explain more extensively what the issue is
 * and why an OIDC interaction is needed.
 *
 * @param oidcInteraction - Interaction object to check.
 */
function assertOidcInteraction(oidcInteraction) {
    if (!oidcInteraction) {
        logger.warn(`Trying to perform OIDC operation without being in an OIDC authentication flow`);
        throw new BadRequestHttpError_1.BadRequestHttpError('This action can only be performed as part of an OIDC authentication flow.', { errorCode: 'E0002' });
    }
}
exports.assertOidcInteraction = assertOidcInteraction;
/**
 * The prompt that is used to track the account ID of a user during an OIDC interaction.
 * The already existing `login` prompt in the {@link InteractionResults}
 * is used to track the WebID that is chosen in an OIDC interaction.
 */
exports.ACCOUNT_PROMPT = 'account';
/**
 * Updates the `oidcInteraction` object with the necessary data in case a prompt gets updated.
 * @param oidcInteraction - Interaction to update.
 * @param result - New data to add to the interaction.
 * @param mergeWithLastSubmission - If this new data needs to be merged with already existing data in the interaction.
 */
async function finishInteraction(oidcInteraction, result, mergeWithLastSubmission) {
    if (mergeWithLastSubmission) {
        result = { ...oidcInteraction.lastSubmission, ...result };
    }
    oidcInteraction.result = result;
    await oidcInteraction.persist();
    return oidcInteraction.returnTo;
}
exports.finishInteraction = finishInteraction;
/**
 * Removes the WebID, the `accountId`, from the OIDC session object,
 * allowing us to replace it with a new value.
 * If there is no session in the Interaction, nothing will happen.
 * @param provider - The OIDC provider.
 * @param oidcInteraction - The current interaction.
 */
async function forgetWebId(provider, oidcInteraction) {
    if (oidcInteraction.session) {
        const session = (await provider.Session.find(oidcInteraction.session.cookie));
        logger.debug(`Forgetting WebID ${session.accountId} in active session`);
        delete session.accountId;
        await session.persist();
    }
}
exports.forgetWebId = forgetWebId;
//# sourceMappingURL=InteractionUtil.js.map