/*
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License.
 */

import {
    ICrypto,
    IPerformanceClient,
    Logger,
} from "@azure/msal-common/browser";
import { InteractionClientBaseV2 } from "./InteractionClientBaseV2.js";
import {
    FlowStartParamsV2,
    FlowSignInStartParamsV2,
    FlowSignUpStartParamsV2,
    FlowChallengeParamsV2,
    FlowSubmitCodeParamsV2,
    FlowSubmitNewPasswordParamsV2,
    FlowSubmitSignInPasswordParamsV2,
    FlowSubmitSignUpAttributesParamsV2,
    FlowSignInWithContinuationParamsV2,
    FlowAuthMethodRegistrationRequiredParamsV2,
    FlowRegisterAuthMethodParamsV2,
    FlowVerifyAuthMethodRegistrationParamsV2,
} from "./parameter/FlowParamsV2.js";
import {
    createFlowMethodSelectionRequiredResultV2,
    createFlowCodeRequiredResultV2,
    createFlowExistingAccountCodeRequiredResultV2,
    createFlowExistingAccountPasswordRequiredResultV2,
    createFlowPasswordRequiredResultV2,
    createFlowSignUpPasswordRequiredResultV2,
    createFlowMFARequiredResultV2,
    createFlowNewPasswordRequiredResultV2,
    createFlowAttributesRequiredResultV2,
    createFlowSignInContinuationRequiredResultV2,
    createFlowCompletedResultV2,
    createFlowAuthMethodRegistrationRequiredResultV2,
    createFlowAuthMethodVerificationRequiredResultV2,
    FLOW_CODE_REQUIRED_V2,
    FLOW_PASSWORD_REQUIRED_V2,
} from "./result/FlowActionResultV2.js";
import type {
    FlowCodeRequiredResultV2,
    FlowExistingAccountChallengeResultV2,
    FlowCompletedResultV2,
    FlowSignInContinuationRequiredResultV2,
    FlowSignInStartResultV2,
    FlowSignUpStartResultV2,
    FlowResetPasswordStartResultV2,
    FlowRequestChallengeResultV2,
    FlowSubmitNewPasswordResultV2,
    FlowSubmitSignInPasswordResultV2,
    FlowSignUpSubmitAttributesResultV2,
    FlowSignUpVerificationResultV2,
    FlowSubmitCodeResultV2,
    FlowAuthMethodRegistrationRequiredResultV2,
    FlowAuthMethodVerificationRequiredResultV2,
} from "./result/FlowActionResultV2.js";
import { BrowserConfiguration } from "../../../../config/Configuration.js";
import { BrowserCacheManager } from "../../../../cache/BrowserCacheManager.js";
import { EventHandler } from "../../../../event/EventHandler.js";
import { INavigationClient } from "../../../../navigation/INavigationClient.js";
import { CustomAuthAuthority } from "../../CustomAuthAuthority.js";
import { CustomAuthApiClientV2 } from "../../network_client/custom_auth_api/v2/CustomAuthApiClientV2.js";
import { CustomAuthError } from "../../error/CustomAuthError.js";
import {
    CONTINUATION_LINK_MISSING,
    RESET_PASSWORD_UNSUPPORTED,
    RESET_PASSWORD_TIMEOUT,
    SIGN_IN_UNSUPPORTED,
    SIGN_UP_UNSUPPORTED,
    UNSUPPORTED_FLOW_STEP,
    UNSUPPORTED_FLOW_TRANSITION,
} from "../../network_client/custom_auth_api/v2/ErrorCodesV2.js";
import { CustomAuthFlowScenarioV2 } from "../../auth_flow/v2/CustomAuthFlowScenarioV2.js";
import * as PublicApiId from "../../telemetry/PublicApiId.js";
import {
    getPublicApiIdV2,
    FlowStepV2,
} from "../../telemetry/FlowApiIdHelperV2.js";
import {
    AuthenticationFactorV2,
    type ChallengeVerificationResultV2,
    type EnrollmentResultV2,
    type VerifyResultV2,
} from "../../network_client/custom_auth_api/v2/result/BaseResultsV2.js";
import {
    AuthenticationMethodTypeV2,
    CHALLENGE_RELATION,
    COLLECT_ATTRIBUTES_RELATION,
    ENROLL_RELATION,
    POLL_RELATION,
    PhoneRegistrationChannelV2,
    RISK_VERIFY_RELATION,
    UPDATE_RELATION,
    VERIFY_RELATION,
    ResponseStateV2,
} from "../../network_client/custom_auth_api/v2/ApiClientConstantsV2.js";
import type { FlowContinuationStateV2 } from "./FlowContinuationStateV2.js";
import type { AuthenticationMethodV2 } from "../../auth_flow/v2/AuthenticationMethodV2.js";
import type { AuthenticationMethodRegistrationV2 } from "../../auth_flow/v2/AuthenticationMethodRegistrationV2.js";
import {
    SignUpSubmitAttributesNextActionV2,
    type SignUpAttributeV2,
    type SignUpSubmitAttributesApiResultV2,
} from "../../network_client/custom_auth_api/v2/result/SignUpResultsV2.js";
import type { AuthMethodRegistrationRequestV2 } from "../../network_client/custom_auth_api/v2/request/RequestsV2.js";
import { InvalidArgumentError } from "../../error/InvalidArgumentError.js";
import type { ResetPasswordPollResultV2 } from "../../network_client/custom_auth_api/v2/result/ResetPasswordResultsV2.js";
import * as ArgumentValidator from "../../utils/ArgumentValidator.js";

const POLL_MAX_ATTEMPTS = 5;
// TODO: Replace this fallback with the server-provided polling interval once available.
const POLL_INTERVAL_MS = 1500;

const delay = (ms: number): Promise<void> =>
    new Promise((resolve) => setTimeout(resolve, ms));

/*
 * Drives server-directed Native Auth V2 flows.
 */
export class FlowInteractionClientV2 extends InteractionClientBaseV2 {
    constructor(
        config: BrowserConfiguration,
        storageImpl: BrowserCacheManager,
        browserCrypto: ICrypto,
        logger: Logger,
        eventHandler: EventHandler,
        navigationClient: INavigationClient,
        performanceClient: IPerformanceClient,
        customAuthAuthority: CustomAuthAuthority,
        protected apiClient: CustomAuthApiClientV2
    ) {
        super(
            config,
            storageImpl,
            browserCrypto,
            logger,
            eventHandler,
            navigationClient,
            performanceClient,
            customAuthAuthority
        );
    }

    /*
     * Starts native auth V2 sign-in.
     */
    async signIn(
        parameters: FlowSignInStartParamsV2
    ): Promise<FlowSignInStartResultV2> {
        const correlationId = parameters.correlationId;
        const context = this.createRequestContext(
            PublicApiId.SIGN_IN_V2_START,
            correlationId
        );

        this.logger.verbose("Starting V2 sign-in.", correlationId);

        const scopes = this.getScopes(parameters.scopes);
        const entryResult = await this.apiClient.authorizeChallengeStart(
            context,
            scopes,
            parameters.claims
        );
        const startResult = await this.apiClient.signInStart(
            this.requireLink(correlationId, entryResult.signInHref, {
                code: SIGN_IN_UNSUPPORTED,
                message:
                    "The authorize-challenge entry response did not include a sign-in link.",
            }),
            {
                continuationToken: entryResult.continuationToken,
                username: parameters.username,
            },
            context
        );
        this.ensureAuthenticationFactor(
            startResult.authenticationFactor,
            AuthenticationFactorV2.SINGLE_FACTOR,
            "sign-in start",
            correlationId
        );

        const continuationState: FlowContinuationStateV2 = {
            continuationToken: startResult.continuationToken,
            scenario: CustomAuthFlowScenarioV2.SignIn,
            scopes,
            links: {},
        };
        const methods = startResult.methods.map((method) => ({
            id: method.id,
            type: method.type ?? "",
            hint: method.hint,
            challengeHref: method.challengeHref,
        }));
        const supportedMethods = this.getSupportedSignInMethods(
            methods,
            correlationId
        );

        if (supportedMethods.length > 1) {
            return createFlowMethodSelectionRequiredResultV2({
                correlationId,
                continuationState,
                methods: supportedMethods,
            });
        }

        const selectedMethod = supportedMethods[0];

        const challengeResult = await this.requestChallenge({
            correlationId,
            continuationState: {
                ...continuationState,
                links: {
                    ...continuationState.links,
                    challenge: selectedMethod.challengeHref,
                },
            },
        });

        if (challengeResult.type === FLOW_CODE_REQUIRED_V2) {
            return {
                ...challengeResult,
                method: selectedMethod,
            };
        }

        return challengeResult;
    }

    /*
     * Starts native auth V2 sign-up.
     */
    async signUp(
        parameters: FlowSignUpStartParamsV2
    ): Promise<FlowSignUpStartResultV2> {
        const correlationId = parameters.correlationId;
        const pendingProfileAttributes =
            ArgumentValidator.filterReservedSignUpAttributesV2(
                parameters.attributes,
                this.logger,
                correlationId
            );
        const context = this.createRequestContext(
            PublicApiId.SIGN_UP_V2_START,
            correlationId
        );

        this.logger.verbose("Starting V2 sign-up.", correlationId);

        const scopes = this.getScopes(parameters.scopes);
        const entryResult = await this.apiClient.authorizeChallengeStart(
            context,
            scopes,
            parameters.claims
        );
        const startResult = await this.apiClient.signUpStart(
            this.requireLink(correlationId, entryResult.signUpHref, {
                code: SIGN_UP_UNSUPPORTED,
                message:
                    "The authorize-challenge entry response did not include a sign-up link.",
            }),
            {
                continuationToken: entryResult.continuationToken,
                username: parameters.username,
            },
            context
        );
        if (startResult.nextAction === VERIFY_RELATION) {
            if (
                startResult.type?.toLowerCase() !==
                AuthenticationMethodTypeV2.EMAIL
            ) {
                const message =
                    "New-account sign-up requires an email code challenge.";
                this.logger.error(message, correlationId);
                throw new CustomAuthError(
                    UNSUPPORTED_FLOW_TRANSITION,
                    message,
                    correlationId
                );
            }

            return createFlowCodeRequiredResultV2({
                correlationId,
                continuationState: {
                    continuationToken: startResult.continuationToken,
                    scenario: CustomAuthFlowScenarioV2.SignUp,
                    scopes,
                    links: {
                        verify: startResult.verifyHref,
                        resend: startResult.resendHref,
                    },
                    signUp: {
                        purpose: "newAccount",
                        pendingProfileAttributes,
                        submittedAttributeIds: [],
                    },
                },
                channel: startResult.type,
                sentTo: startResult.hint,
                codeLength: startResult.codeLength,
            });
        }

        const continuationState: FlowContinuationStateV2 = {
            continuationToken: startResult.continuationToken,
            scenario: CustomAuthFlowScenarioV2.SignUp,
            scopes,
            links: {},
            signUp: {
                purpose: "existingAccount",
            },
        };
        this.ensureAuthenticationFactor(
            startResult.authenticationFactor,
            AuthenticationFactorV2.SINGLE_FACTOR,
            "existing-account sign-up",
            correlationId
        );
        const supportedMethods = startResult.methods
            .map((method) => ({
                id: method.id,
                type: method.type ?? "",
                hint: method.hint,
                challengeHref: method.challengeHref,
            }))
            .filter((method) => {
                const methodType = method.type.toLowerCase();
                return (
                    methodType === AuthenticationMethodTypeV2.EMAIL ||
                    methodType === AuthenticationMethodTypeV2.PASSWORD
                );
            });

        if (supportedMethods.length === 0) {
            throw new CustomAuthError(
                UNSUPPORTED_FLOW_TRANSITION,
                "The existing-account sign-up response must include an email or password method.",
                correlationId
            );
        }

        if (supportedMethods.length > 1) {
            return createFlowMethodSelectionRequiredResultV2({
                correlationId,
                continuationState,
                methods: supportedMethods,
            });
        }

        const selectedMethod = supportedMethods[0];
        const challengeResult = await this.requestChallenge({
            correlationId,
            continuationState: {
                ...continuationState,
                links: {
                    challenge: selectedMethod.challengeHref,
                },
            },
        });

        return this.toExistingAccountChallengeResult(
            challengeResult,
            selectedMethod,
            correlationId
        );
    }

    /*
     * Starts native auth V2 password reset.
     */
    async resetPassword(
        parameters: FlowStartParamsV2
    ): Promise<FlowResetPasswordStartResultV2> {
        const correlationId = parameters.correlationId;
        const context = this.createRequestContext(
            PublicApiId.RESET_PASSWORD_V2_START,
            correlationId
        );

        this.logger.verbose(
            "Starting V2 self-service password reset.",
            correlationId
        );

        const scopes = this.getScopes(parameters.scopes);
        const entryResult = await this.apiClient.authorizeChallengeStart(
            context,
            scopes,
            parameters.claims
        );
        const startResult = await this.apiClient.resetPasswordStart(
            this.requireLink(correlationId, entryResult.resetPasswordHref, {
                code: RESET_PASSWORD_UNSUPPORTED,
                message:
                    "The authorize-challenge entry response did not include a reset-password link.",
            }),
            {
                username: parameters.username,
                continuationToken: entryResult.continuationToken,
            },
            context
        );
        this.ensureAuthenticationFactor(
            startResult.authenticationFactor,
            AuthenticationFactorV2.SINGLE_FACTOR,
            "password-reset start",
            correlationId
        );
        const continuationState: FlowContinuationStateV2 = {
            continuationToken: startResult.continuationToken,
            scenario: CustomAuthFlowScenarioV2.PasswordReset,
            scopes,
            links: {},
        };
        const methods = startResult.methods.map((method) => ({
            id: method.id,
            type: method.type ?? "",
            hint: method.hint,
            challengeHref: method.challengeHref,
        }));

        if (methods.length === 0) {
            const message =
                "The password-reset start response did not include an authentication method.";
            this.logger.error(message, correlationId);
            throw new CustomAuthError(
                UNSUPPORTED_FLOW_TRANSITION,
                message,
                correlationId
            );
        }

        if (methods.length > 1) {
            this.logger.verbose(
                "V2 self-service password reset method selection required.",
                correlationId
            );

            return createFlowMethodSelectionRequiredResultV2({
                correlationId,
                continuationState,
                methods,
            });
        }

        const selectedMethod = methods[0];
        const challengeResult = await this.requestChallenge({
            correlationId,
            continuationState: {
                ...continuationState,
                links: {
                    challenge: selectedMethod.challengeHref,
                },
            },
        });

        if (
            challengeResult.type === FLOW_CODE_REQUIRED_V2 &&
            (challengeResult.channel?.toLowerCase() ===
                AuthenticationMethodTypeV2.EMAIL ||
                challengeResult.channel?.toLowerCase() ===
                    AuthenticationMethodTypeV2.SMS)
        ) {
            return {
                ...challengeResult,
                method: selectedMethod,
            };
        }

        const channel =
            challengeResult.type === FLOW_CODE_REQUIRED_V2
                ? challengeResult.channel
                : AuthenticationMethodTypeV2.PASSWORD;
        const message = `Challenge type '${challengeResult.type}' with channel '${channel}' is not supported for password reset.`;
        this.logger.error(message, correlationId);
        throw new CustomAuthError(
            UNSUPPORTED_FLOW_TRANSITION,
            message,
            correlationId
        );
    }

    /*
     * Requests a challenge for the selected authentication method.
     */
    async requestChallenge(
        parameters: FlowChallengeParamsV2
    ): Promise<FlowRequestChallengeResultV2> {
        const challengeResult = await this.sendMethodChallenge(
            parameters,
            "requestChallenge"
        );
        const challengeType = challengeResult.type;
        const normalizedChallengeType = challengeType?.toLowerCase();
        const continuationState = this.createChallengeContinuationState(
            parameters.continuationState,
            challengeResult
        );

        if (normalizedChallengeType === AuthenticationMethodTypeV2.PASSWORD) {
            return createFlowPasswordRequiredResultV2({
                correlationId: parameters.correlationId,
                continuationState,
            });
        }

        if (
            normalizedChallengeType === AuthenticationMethodTypeV2.EMAIL ||
            normalizedChallengeType === AuthenticationMethodTypeV2.SMS
        ) {
            return createFlowCodeRequiredResultV2({
                correlationId: parameters.correlationId,
                continuationState,
                channel: challengeType,
                sentTo: challengeResult.hint,
                codeLength: challengeResult.codeLength,
            });
        }

        const message = challengeType
            ? `Challenge type '${challengeType}' is not supported.`
            : "Challenge type is missing.";
        this.logger.error(message, parameters.correlationId);
        throw new CustomAuthError(
            UNSUPPORTED_FLOW_TRANSITION,
            message,
            parameters.correlationId
        );
    }

    /*
     * Registers the selected authentication method.
     */
    async registerAuthMethod(
        parameters: FlowRegisterAuthMethodParamsV2
    ): Promise<FlowAuthMethodVerificationRequiredResultV2> {
        const { continuationState, correlationId } = parameters;
        if (!parameters.verificationContact?.trim()) {
            throw new InvalidArgumentError(
                "verificationContact",
                correlationId
            );
        }

        const registrationRequest = this.createRegistrationRequest(
            parameters.method,
            parameters.verificationContact,
            continuationState.continuationToken,
            correlationId
        );
        const context = this.createRequestContext(
            PublicApiId.JIT_V2_ENROLL_AUTH_METHOD,
            correlationId
        );

        this.logger.verbose(
            "Registering a V2 authentication method.",
            correlationId
        );
        const result = await this.apiClient.enrollAuthMethod(
            this.requireLink(correlationId, parameters.method.enrollHref),
            registrationRequest,
            context
        );

        return this.createAuthMethodVerificationRequiredResult(
            continuationState,
            result,
            correlationId
        );
    }

    /*
     * Activates the registered authentication method.
     */
    async verifyAuthMethodRegistration(
        parameters: FlowVerifyAuthMethodRegistrationParamsV2
    ): Promise<FlowCompletedResultV2 | FlowSignInContinuationRequiredResultV2> {
        const { continuationState, correlationId } = parameters;

        const context = this.createRequestContext(
            PublicApiId.JIT_V2_SUBMIT_CHALLENGE,
            correlationId
        );
        this.logger.verbose(
            "Activating a V2 authentication method.",
            correlationId
        );
        const result = await this.apiClient.activateAuthMethod(
            this.requireLink(correlationId, continuationState.links.activate),
            {
                continuationToken: continuationState.continuationToken,
                otp: parameters.code,
            },
            context
        );

        if (
            continuationState.scenario === CustomAuthFlowScenarioV2.SignUp ||
            continuationState.scenario ===
                CustomAuthFlowScenarioV2.PasswordReset
        ) {
            return createFlowSignInContinuationRequiredResultV2({
                correlationId,
                continuationState: {
                    ...continuationState,
                    continuationToken: result.continuationToken,
                    links: {},
                },
            });
        }

        return this.completeSignInAfterVerification(
            continuationState,
            result.continuationToken,
            correlationId
        );
    }

    /*
     * Requests a replacement authentication-method activation challenge.
     */
    async resendAuthMethodRegistrationChallenge(
        parameters: FlowChallengeParamsV2
    ): Promise<FlowAuthMethodVerificationRequiredResultV2> {
        const { continuationState, correlationId } = parameters;
        const context = this.createRequestContext(
            PublicApiId.JIT_V2_RESEND_CHALLENGE,
            correlationId
        );
        this.logger.verbose(
            "Resending a V2 authentication-method activation challenge.",
            correlationId
        );
        const result =
            await this.apiClient.resendAuthMethodRegistrationChallenge(
                this.requireLink(correlationId, continuationState.links.resend),
                {
                    continuationToken: continuationState.continuationToken,
                },
                context
            );

        return this.createAuthMethodVerificationRequiredResult(
            continuationState,
            result,
            correlationId
        );
    }

    /*
     * Verifies the submitted one-time code.
     */
    async submitCode(
        parameters: FlowSubmitCodeParamsV2
    ): Promise<FlowSubmitCodeResultV2> {
        const continuationState = parameters.continuationState;
        const correlationId = parameters.correlationId;
        const context = this.createRequestContext(
            this.resolveStepApiId(
                continuationState.scenario,
                "submitCode",
                correlationId,
                parameters.authenticationFactor
            ),
            correlationId
        );

        this.logger.verbose("Submitting V2 one-time code.", correlationId);

        const verifyHref = this.requireLink(
            correlationId,
            continuationState.links.verify
        );
        const verifyRequest = {
            continuationToken: continuationState.continuationToken,
            otp: parameters.code,
        };
        const verifyResult = await this.apiClient.verifyChallenge(
            verifyHref,
            verifyRequest,
            context
        );

        if (
            continuationState.scenario ===
                CustomAuthFlowScenarioV2.PasswordReset &&
            parameters.authenticationFactor ===
                AuthenticationFactorV2.MULTI_FACTOR &&
            verifyResult.nextAction === ResponseStateV2.CONTINUE
        ) {
            return createFlowSignInContinuationRequiredResultV2({
                correlationId,
                continuationState: {
                    ...continuationState,
                    continuationToken: verifyResult.continuationToken,
                    links: {},
                },
            });
        }

        if (
            continuationState.scenario ===
                CustomAuthFlowScenarioV2.PasswordReset &&
            parameters.authenticationFactor !==
                AuthenticationFactorV2.MULTI_FACTOR &&
            verifyResult.nextAction === UPDATE_RELATION
        ) {
            return createFlowNewPasswordRequiredResultV2({
                correlationId,
                continuationState: {
                    continuationToken: verifyResult.continuationToken,
                    scenario: continuationState.scenario,
                    scopes: continuationState.scopes,
                    links: { update: verifyResult.updateHref },
                },
            });
        }

        if (continuationState.scenario === CustomAuthFlowScenarioV2.SignIn) {
            return this.handleSignInVerification(
                continuationState,
                verifyResult,
                correlationId
            );
        }

        if (
            continuationState.scenario === CustomAuthFlowScenarioV2.SignUp &&
            continuationState.signUp?.purpose === "existingAccount"
        ) {
            return this.handleSignInVerification(
                continuationState,
                verifyResult,
                correlationId
            );
        }

        if (continuationState.scenario === CustomAuthFlowScenarioV2.SignUp) {
            return this.handleSignUpVerification(
                continuationState,
                verifyResult,
                correlationId
            );
        }

        const message = `Verification next action '${verifyResult.nextAction}' is not supported for the '${continuationState.scenario}' flow.`;
        this.logger.error(message, correlationId);

        throw new CustomAuthError(
            UNSUPPORTED_FLOW_TRANSITION,
            message,
            correlationId
        );
    }

    /*
     * Requests a replacement one-time code.
     */
    async resendCode(
        parameters: FlowChallengeParamsV2
    ): Promise<FlowCodeRequiredResultV2> {
        const challengeResult = await this.sendMethodChallenge(
            parameters,
            "resendCode"
        );
        const challengeType = challengeResult.type?.toLowerCase();
        if (
            challengeType !== AuthenticationMethodTypeV2.EMAIL &&
            challengeType !== AuthenticationMethodTypeV2.SMS
        ) {
            const message =
                "A replacement code requires an email or SMS code challenge.";
            this.logger.error(message, parameters.correlationId);
            throw new CustomAuthError(
                UNSUPPORTED_FLOW_TRANSITION,
                message,
                parameters.correlationId
            );
        }

        return createFlowCodeRequiredResultV2({
            correlationId: parameters.correlationId,
            continuationState: this.createChallengeContinuationState(
                parameters.continuationState,
                challengeResult
            ),
            channel: challengeResult.type,
            sentTo: challengeResult.hint,
            codeLength: challengeResult.codeLength,
        });
    }

    async submitSignUpAttributes(
        parameters: FlowSubmitSignUpAttributesParamsV2
    ): Promise<FlowSignUpSubmitAttributesResultV2> {
        const {
            continuationState,
            correlationId,
            attributes: submittedAttributes,
        } = parameters;
        const context = this.createRequestContext(
            this.resolveStepApiId(
                continuationState.scenario,
                "submitAttributes",
                correlationId
            ),
            correlationId
        );

        this.logger.verbose(
            "Submitting additional V2 sign-up attributes.",
            correlationId
        );

        const submittedAttributeIds = Object.keys(submittedAttributes);
        const submitResult = await this.apiClient.submitSignUpAttributes(
            this.requireLink(
                correlationId,
                continuationState.links.submitAttributes
            ),
            {
                continuationToken: continuationState.continuationToken,
                attributes: submittedAttributes,
            },
            context
        );

        return this.toSignUpSubmitAttributesResult(
            submitResult,
            {
                ...continuationState,
                signUp: {
                    purpose: "newAccount",
                    submittedAttributeIds: [
                        ...new Set([
                            ...(continuationState.signUp
                                ?.submittedAttributeIds ?? []),
                            ...submittedAttributeIds,
                        ]),
                    ],
                },
            },
            correlationId
        );
    }

    /*
     * Submits the new password and polls for the next action: method registration,
     * MFA, or a continuation for explicit sign-in.
     */
    async submitNewPassword(
        parameters: FlowSubmitNewPasswordParamsV2
    ): Promise<FlowSubmitNewPasswordResultV2> {
        const continuationState = parameters.continuationState;
        const correlationId = parameters.correlationId;
        const context = this.createRequestContext(
            this.resolveStepApiId(
                continuationState.scenario,
                "submitNewPassword",
                correlationId
            ),
            correlationId
        );

        this.logger.verbose("Submitting V2 new password.", correlationId);

        const updateResult = await this.apiClient.submitNewPassword(
            this.requireLink(correlationId, continuationState.links.update),
            {
                continuationToken: continuationState.continuationToken,
                newPassword: parameters.newPassword,
            },
            context
        );

        let pollToken = updateResult.continuationToken;
        let pollHref = updateResult.pollHref;
        let pollResult: ResetPasswordPollResultV2 | undefined;
        let isPolling = false;

        for (let attempt = 1; attempt <= POLL_MAX_ATTEMPTS; attempt++) {
            pollResult = await this.apiClient.poll(
                pollHref,
                { continuationToken: pollToken },
                context
            );

            isPolling = pollResult.nextAction === POLL_RELATION;
            if (pollResult.nextAction !== POLL_RELATION) {
                break;
            }

            pollToken = pollResult.continuationToken;
            pollHref = this.requireLink(correlationId, pollResult.pollHref);

            if (attempt < POLL_MAX_ATTEMPTS) {
                await delay(POLL_INTERVAL_MS);
            }
        }

        if (!pollResult || isPolling) {
            const message =
                "The password reset did not complete within the allotted number of polling attempts.";
            this.logger.error(message, correlationId);

            throw new CustomAuthError(
                RESET_PASSWORD_TIMEOUT,
                message,
                correlationId
            );
        }

        if (pollResult.nextAction === ENROLL_RELATION && pollResult.methods) {
            return this.createAuthMethodRegistrationRequiredResult({
                correlationId,
                continuationState: {
                    ...continuationState,
                    continuationToken: pollResult.continuationToken,
                    links: {},
                },
                methods: pollResult.methods,
            });
        }

        if (pollResult.nextAction === CHALLENGE_RELATION) {
            if (!pollResult.authenticationFactor) {
                const message =
                    "Password-reset MFA challenge is missing its authentication factor.";
                this.logger.error(message, correlationId);
                throw new CustomAuthError(
                    UNSUPPORTED_FLOW_TRANSITION,
                    message,
                    correlationId
                );
            }

            this.ensureAuthenticationFactor(
                pollResult.authenticationFactor,
                AuthenticationFactorV2.MULTI_FACTOR,
                "after password reset",
                correlationId
            );

            return createFlowMFARequiredResultV2({
                correlationId,
                continuationState: {
                    continuationToken: pollResult.continuationToken,
                    scenario: continuationState.scenario,
                    scopes: continuationState.scopes,
                    links: {},
                },
                methods: pollResult.methods.map((method) => ({
                    id: method.id,
                    type: method.type ?? "",
                    hint: method.hint,
                    challengeHref: method.challengeHref,
                })),
            });
        }

        if (pollResult.nextAction === ResponseStateV2.CONTINUE) {
            this.logger.verbose(
                "V2 password reset applied; sign-in required.",
                correlationId
            );

            return createFlowSignInContinuationRequiredResultV2({
                correlationId,
                continuationState: {
                    continuationToken: pollResult.continuationToken,
                    scenario: continuationState.scenario,
                    scopes: continuationState.scopes,
                    links: {},
                },
            });
        }

        const message = `Password reset poll next action '${pollResult.nextAction}' is not supported.`;
        this.logger.error(message, correlationId);
        throw new CustomAuthError(
            UNSUPPORTED_FLOW_TRANSITION,
            message,
            correlationId
        );
    }

    /*
     * Verifies the sign-in password.
     */
    async submitSignInPassword(
        parameters: FlowSubmitSignInPasswordParamsV2
    ): Promise<FlowSubmitSignInPasswordResultV2> {
        const verifyResult = await this.verifySignInPassword(parameters);

        return this.handleSignInVerification(
            parameters.continuationState,
            verifyResult,
            parameters.correlationId
        );
    }

    /*
     * Signs the user in from a completed flow.
     */
    async signInWithContinuation(
        parameters: FlowSignInWithContinuationParamsV2
    ): Promise<FlowCompletedResultV2> {
        const continuationState = parameters.continuationState;
        const correlationId = parameters.correlationId;
        const apiId = this.resolveStepApiId(
            continuationState.scenario,
            "signInWithContinuation",
            correlationId
        );
        const context = this.createRequestContext(apiId, correlationId);

        this.logger.verbose(
            "Signing in with a V2 continuation.",
            correlationId
        );

        const tokenResponse = await this.apiClient.completeWithTokens(
            {
                continuationToken: continuationState.continuationToken,
            },
            context
        );

        const authenticationResult = await this.handleTokenResponse(
            tokenResponse,
            continuationState.scopes,
            correlationId,
            apiId
        );

        this.logger.verbose(
            "V2 continuation sign-in completed.",
            correlationId
        );

        return createFlowCompletedResultV2({
            correlationId,
            authenticationResult,
        });
    }

    private async handleSignInVerification(
        continuationState: FlowContinuationStateV2,
        verifyResult: VerifyResultV2,
        correlationId: string
    ): Promise<FlowSubmitSignInPasswordResultV2> {
        if (verifyResult.nextAction === ENROLL_RELATION) {
            return this.createAuthMethodRegistrationRequiredResult({
                correlationId,
                continuationState: {
                    ...continuationState,
                    continuationToken: verifyResult.continuationToken,
                    links: {},
                },
                methods: verifyResult.methods,
            });
        }

        if (verifyResult.nextAction === CHALLENGE_RELATION) {
            this.ensureAuthenticationFactor(
                verifyResult.authenticationFactor,
                AuthenticationFactorV2.MULTI_FACTOR,
                "after authentication verification",
                correlationId
            );

            return createFlowMFARequiredResultV2({
                correlationId,
                continuationState: {
                    ...continuationState,
                    continuationToken: verifyResult.continuationToken,
                    links: {},
                },
                methods: verifyResult.methods.map((method) => ({
                    id: method.id,
                    type: method.type ?? "",
                    hint: method.hint,
                    challengeHref: method.challengeHref,
                })),
            });
        }

        if (verifyResult.nextAction === ResponseStateV2.CONTINUE) {
            return this.completeSignInAfterVerification(
                continuationState,
                verifyResult.continuationToken,
                correlationId
            );
        }

        const message = `Verification next action '${verifyResult.nextAction}' is not supported for authentication.`;
        this.logger.error(message, correlationId);
        throw new CustomAuthError(
            UNSUPPORTED_FLOW_TRANSITION,
            message,
            correlationId
        );
    }

    private async handleSignUpVerification(
        continuationState: FlowContinuationStateV2,
        verifyResult: VerifyResultV2,
        correlationId: string
    ): Promise<FlowSignUpVerificationResultV2> {
        if (verifyResult.nextAction === COLLECT_ATTRIBUTES_RELATION) {
            const requestedAttributes = verifyResult.attributes;
            const requestedPasswordAttribute = requestedAttributes.find(
                (attribute) =>
                    attribute.attributeId.toLowerCase() === "password"
            );
            const nextContinuationState: FlowContinuationStateV2 = {
                ...continuationState,
                continuationToken: verifyResult.continuationToken,
                links: {
                    submitAttributes: verifyResult.submitAttributesHref,
                },
            };
            const pendingProfileAttributes =
                continuationState.signUp?.pendingProfileAttributes;

            if (
                pendingProfileAttributes &&
                Object.keys(pendingProfileAttributes).length > 0
            ) {
                return this.submitSignUpAttributes({
                    correlationId,
                    continuationState: nextContinuationState,
                    attributes: pendingProfileAttributes,
                });
            }

            if (requestedPasswordAttribute) {
                return createFlowSignUpPasswordRequiredResultV2({
                    correlationId,
                    continuationState: nextContinuationState,
                    requestedPasswordAttribute,
                });
            }

            return createFlowAttributesRequiredResultV2({
                correlationId,
                continuationState: nextContinuationState,
                attributes: requestedAttributes,
            });
        }

        if (verifyResult.nextAction === ENROLL_RELATION) {
            return this.createAuthMethodRegistrationRequiredResult({
                correlationId,
                continuationState: {
                    ...continuationState,
                    continuationToken: verifyResult.continuationToken,
                    links: {},
                },
                methods: verifyResult.methods,
            });
        }

        if (verifyResult.nextAction === ResponseStateV2.CONTINUE) {
            return createFlowSignInContinuationRequiredResultV2({
                correlationId,
                continuationState: {
                    ...continuationState,
                    continuationToken: verifyResult.continuationToken,
                    links: {},
                },
            });
        }

        const message = `Verification next action '${verifyResult.nextAction}' is not supported for the '${continuationState.scenario}' flow.`;
        this.logger.error(message, correlationId);
        throw new CustomAuthError(
            UNSUPPORTED_FLOW_TRANSITION,
            message,
            correlationId
        );
    }

    private getSupportedSignInMethods(
        methods: AuthenticationMethodV2[],
        correlationId: string
    ): AuthenticationMethodV2[] {
        const supportedMethods = methods.filter((method) => {
            const methodType = method.type.toLowerCase();
            return (
                methodType === AuthenticationMethodTypeV2.EMAIL ||
                methodType === AuthenticationMethodTypeV2.PASSWORD ||
                methodType === AuthenticationMethodTypeV2.SMS
            );
        });

        if (supportedMethods.length > 0) {
            return supportedMethods;
        }

        const message =
            "The sign-in start response did not include a supported email, SMS, or password method.";
        this.logger.error(message, correlationId);
        throw new CustomAuthError(
            UNSUPPORTED_FLOW_TRANSITION,
            message,
            correlationId
        );
    }

    private createRegistrationRequest(
        method: AuthenticationMethodRegistrationV2,
        verificationContact: string,
        continuationToken: string,
        correlationId: string
    ): AuthMethodRegistrationRequestV2 {
        if (method.type === AuthenticationMethodTypeV2.EMAIL) {
            return {
                continuationToken,
                email: verificationContact,
            };
        }

        const [channel] = method.channels ?? [];
        if (
            method.type === AuthenticationMethodTypeV2.PHONE &&
            channel === PhoneRegistrationChannelV2.SMS
        ) {
            return {
                continuationToken,
                phoneNumber: verificationContact,
                channel,
            };
        }

        throw new CustomAuthError(
            UNSUPPORTED_FLOW_TRANSITION,
            "The selected authentication method is not supported for registration.",
            correlationId
        );
    }

    private createAuthMethodRegistrationRequiredResult(
        parameters: FlowAuthMethodRegistrationRequiredParamsV2
    ): FlowAuthMethodRegistrationRequiredResultV2 {
        const { correlationId, continuationState } = parameters;
        const supportedMethods = parameters.methods.filter((method) => {
            const methodType = method.type.trim().toLowerCase();
            return (
                methodType === AuthenticationMethodTypeV2.EMAIL ||
                (methodType === AuthenticationMethodTypeV2.PHONE &&
                    method.channels?.includes(PhoneRegistrationChannelV2.SMS))
            );
        });

        if (supportedMethods.length === 0) {
            const message =
                "The enrollment response did not include a supported registration method.";
            this.logger.error(message, correlationId);
            throw new CustomAuthError(
                UNSUPPORTED_FLOW_TRANSITION,
                message,
                correlationId
            );
        }

        const methods = supportedMethods.map((method) => {
            const methodType = method.type.trim().toLowerCase();
            const channel = method.channels?.find(
                (candidate) => candidate === PhoneRegistrationChannelV2.SMS
            );

            if (methodType === AuthenticationMethodTypeV2.EMAIL) {
                return {
                    type: AuthenticationMethodTypeV2.EMAIL,
                    enrollHref: this.requireLink(
                        correlationId,
                        method.enrollHref
                    ),
                };
            }

            if (
                methodType === AuthenticationMethodTypeV2.PHONE &&
                channel === PhoneRegistrationChannelV2.SMS
            ) {
                return {
                    type: AuthenticationMethodTypeV2.PHONE,
                    channels: [channel],
                    enrollHref: this.requireLink(
                        correlationId,
                        method.enrollHref
                    ),
                };
            }

            const message =
                "The enrollment response included an unsupported registration method.";
            this.logger.error(message, correlationId);
            throw new CustomAuthError(
                UNSUPPORTED_FLOW_TRANSITION,
                message,
                correlationId
            );
        });

        return createFlowAuthMethodRegistrationRequiredResultV2({
            correlationId,
            continuationState,
            methods,
        });
    }

    private createAuthMethodVerificationRequiredResult(
        continuationState: FlowContinuationStateV2,
        result: EnrollmentResultV2,
        correlationId: string
    ): FlowAuthMethodVerificationRequiredResultV2 {
        return createFlowAuthMethodVerificationRequiredResultV2({
            correlationId,
            continuationState: {
                ...continuationState,
                continuationToken: result.continuationToken,
                links: {
                    activate: this.requireLink(
                        correlationId,
                        result.activateHref
                    ),
                    resend: result.resendHref,
                },
            },
            sentTo: result.hint,
            codeLength: result.codeLength,
        });
    }

    private toSignUpSubmitAttributesResult(
        result: SignUpSubmitAttributesApiResultV2,
        continuationState: FlowContinuationStateV2,
        correlationId: string
    ): FlowSignUpSubmitAttributesResultV2 {
        const nextAction: string = result.nextAction;

        if (result.nextAction === SignUpSubmitAttributesNextActionV2.ENROLL) {
            return this.createAuthMethodRegistrationRequiredResult({
                correlationId,
                continuationState: {
                    ...continuationState,
                    continuationToken: result.continuationToken,
                    links: {},
                },
                methods: result.methods,
            });
        }

        if (
            result.nextAction ===
            SignUpSubmitAttributesNextActionV2.COLLECT_ATTRIBUTES
        ) {
            const requestedAttributes = result.attributes;
            this.ensureValidSignUpAttributeCollectionAfterSubmission(
                requestedAttributes,
                continuationState,
                correlationId
            );
            const nextContinuationState: FlowContinuationStateV2 = {
                ...continuationState,
                continuationToken: result.continuationToken,
                links: {
                    submitAttributes: result.submitAttributesHref,
                },
            };

            const requestedPasswordAttribute = requestedAttributes.find(
                (attribute) =>
                    attribute.attributeId.toLowerCase() === "password"
            );
            if (requestedPasswordAttribute) {
                return createFlowSignUpPasswordRequiredResultV2({
                    correlationId,
                    continuationState: nextContinuationState,
                    requestedPasswordAttribute,
                });
            }

            return createFlowAttributesRequiredResultV2({
                correlationId,
                continuationState: nextContinuationState,
                attributes: requestedAttributes,
            });
        }

        if (result.nextAction === SignUpSubmitAttributesNextActionV2.CONTINUE) {
            return createFlowSignInContinuationRequiredResultV2({
                correlationId,
                continuationState: {
                    ...continuationState,
                    continuationToken: result.continuationToken,
                    links: {},
                },
            });
        }

        const message = `Sign-up attribute submission next action '${nextAction}' is not supported.`;
        this.logger.error(message, correlationId);
        throw new CustomAuthError(
            UNSUPPORTED_FLOW_TRANSITION,
            message,
            correlationId
        );
    }

    private ensureValidSignUpAttributeCollectionAfterSubmission(
        requestedAttributes: SignUpAttributeV2[],
        continuationState: FlowContinuationStateV2,
        correlationId: string
    ): void {
        const submittedAttributeIds =
            continuationState.signUp?.submittedAttributeIds ?? [];
        const hasSubmittedPassword = submittedAttributeIds.some(
            (attributeId) => attributeId.toLowerCase() === "password"
        );
        const invalidAttribute = requestedAttributes.find(
            (requestedAttribute) =>
                requestedAttribute.attributeId.toLowerCase() === "password"
                    ? hasSubmittedPassword
                    : submittedAttributeIds.includes(
                          requestedAttribute.attributeId
                      )
        );
        if (invalidAttribute) {
            const message =
                invalidAttribute.attributeId.toLowerCase() === "password"
                    ? "The sign-up API cannot request password collection after attribute submission."
                    : "The sign-up API requested an attribute that was already successfully submitted.";
            this.logger.error(message, correlationId);
            throw new CustomAuthError(
                UNSUPPORTED_FLOW_TRANSITION,
                message,
                correlationId
            );
        }
    }

    private ensureAuthenticationFactor(
        authenticationFactor: AuthenticationFactorV2,
        expectedFactor: AuthenticationFactorV2,
        transition: string,
        correlationId: string
    ): void {
        if (authenticationFactor === expectedFactor) {
            return;
        }

        const message = `Authentication factor '${authenticationFactor}' is not supported for ${transition}.`;
        this.logger.error(message, correlationId);
        throw new CustomAuthError(
            UNSUPPORTED_FLOW_TRANSITION,
            message,
            correlationId
        );
    }

    private toExistingAccountChallengeResult(
        challengeResult: FlowRequestChallengeResultV2,
        method: AuthenticationMethodV2,
        correlationId: string
    ): FlowExistingAccountChallengeResultV2 {
        if (
            challengeResult.type === FLOW_CODE_REQUIRED_V2 &&
            challengeResult.channel?.toLowerCase() ===
                AuthenticationMethodTypeV2.EMAIL
        ) {
            return createFlowExistingAccountCodeRequiredResultV2({
                correlationId,
                continuationState: challengeResult.continuationState,
                method,
                channel: challengeResult.channel,
                sentTo: challengeResult.sentTo,
                codeLength: challengeResult.codeLength,
            });
        }

        if (challengeResult.type === FLOW_PASSWORD_REQUIRED_V2) {
            return createFlowExistingAccountPasswordRequiredResultV2({
                correlationId,
                continuationState: challengeResult.continuationState,
            });
        }

        const message =
            "Existing-account sign-up requires an email code challenge or a password challenge.";
        this.logger.error(message, correlationId);
        throw new CustomAuthError(
            UNSUPPORTED_FLOW_TRANSITION,
            message,
            correlationId
        );
    }

    private async verifySignInPassword(
        parameters: FlowSubmitSignInPasswordParamsV2
    ): Promise<VerifyResultV2> {
        const { continuationState, correlationId } = parameters;
        const context = this.createRequestContext(
            this.resolveStepApiId(
                continuationState.scenario,
                "submitPassword",
                correlationId
            ),
            correlationId
        );

        this.logger.verbose(
            "Submitting V2 authentication password.",
            correlationId
        );

        return this.apiClient.verifyChallenge(
            this.requireLink(correlationId, continuationState.links.verify),
            {
                continuationToken: continuationState.continuationToken,
                password: parameters.password,
            },
            context
        );
    }

    private completeSignInAfterVerification(
        continuationState: FlowContinuationStateV2,
        continuationToken: string,
        correlationId: string
    ): Promise<FlowCompletedResultV2> {
        return this.signInWithContinuation({
            correlationId,
            continuationState: {
                ...continuationState,
                continuationToken,
                links: {},
            },
        });
    }

    private async sendMethodChallenge(
        parameters: FlowChallengeParamsV2,
        step: "requestChallenge" | "resendCode"
    ): Promise<ChallengeVerificationResultV2> {
        const continuationState = parameters.continuationState;
        const correlationId = parameters.correlationId;
        const challengeHref =
            step === "resendCode"
                ? continuationState.links.resend
                : continuationState.links.challenge;
        const context = this.createRequestContext(
            this.resolveStepApiId(
                continuationState.scenario,
                step,
                correlationId,
                parameters.authenticationFactor
            ),
            correlationId
        );

        this.logger.verbose(
            step === "resendCode"
                ? "Resending V2 one-time code."
                : "Requesting V2 challenge.",
            correlationId
        );

        const challengeResult = await this.apiClient.requestChallenge(
            this.requireLink(correlationId, challengeHref),
            { continuationToken: continuationState.continuationToken },
            context
        );
        const nextAction: string = challengeResult.nextAction;

        if (challengeResult.nextAction === VERIFY_RELATION) {
            return challengeResult;
        }

        if (challengeResult.nextAction === RISK_VERIFY_RELATION) {
            return this.apiClient.verifyRisk(
                challengeResult.riskVerifyHref,
                { continuationToken: challengeResult.continuationToken },
                context
            );
        }

        const message = `Challenge next action '${nextAction}' is not supported.`;
        this.logger.error(message, correlationId);
        throw new CustomAuthError(
            UNSUPPORTED_FLOW_TRANSITION,
            message,
            correlationId
        );
    }

    private createChallengeContinuationState(
        continuationState: FlowContinuationStateV2,
        challengeResult: ChallengeVerificationResultV2
    ): FlowContinuationStateV2 {
        return {
            ...continuationState,
            continuationToken: challengeResult.continuationToken,
            links: {
                challenge: continuationState.links.challenge,
                verify: challengeResult.verifyHref,
                resend:
                    challengeResult.resendHref ??
                    continuationState.links.resend,
            },
        };
    }

    private resolveStepApiId(
        scenario: CustomAuthFlowScenarioV2,
        step: FlowStepV2,
        correlationId: string,
        authenticationFactor?: AuthenticationFactorV2
    ): number {
        const apiId = getPublicApiIdV2(scenario, step, authenticationFactor);

        if (apiId === undefined) {
            const message = `No telemetry API id is registered for step '${step}' of the '${scenario}' flow.`;
            this.logger.error(message, correlationId);

            throw new CustomAuthError(
                UNSUPPORTED_FLOW_STEP,
                message,
                correlationId
            );
        }

        return apiId;
    }

    private requireLink(
        correlationId: string,
        href: string | undefined,
        missingLinkError?: { code: string; message: string }
    ): string {
        if (typeof href !== "string" || !href.trim()) {
            const errorCode =
                missingLinkError?.code ?? CONTINUATION_LINK_MISSING;
            const message =
                missingLinkError?.message ??
                "The continuation state is missing a link required to advance the flow.";
            this.logger.error(message, correlationId);

            throw new CustomAuthError(errorCode, message, correlationId);
        }

        return href;
    }
}
