@page "/Account/Manage/ResetAuthenticator"

@using Microsoft.AspNetCore.Identity
@using Wave.Data

@inject UserManager<ApplicationUser> UserManager
@inject SignInManager<ApplicationUser> SignInManager
@inject IdentityUserAccessor UserAccessor
@inject IdentityRedirectManager RedirectManager
@inject ILogger<ResetAuthenticator> Logger
@inject IStringLocalizer<ResetAuthenticator> Localizer

<PageTitle>@Localizer["Title"]</PageTitle>

<StatusMessage />

<BoardComponent>
    <BoardCardComponent Heading="@Localizer["Title"]">
        <Alert Type="Alert.MessageType.Warning" CanRemove="false">
            <strong>@Localizer["ResetAuthenticator_Title"]</strong>
            <p>@Localizer["ResetAuthenticator_Message"]</p>
        </Alert>
        <form @formname="reset-authenticator" @onsubmit="OnSubmitAsync" method="post" class="w-full">
            <AntiforgeryToken />
            <button class="btn btn-error w-full mt-3" type="submit">@Localizer["ResetAuthenticator_Submit"]</button>
        </form>
    </BoardCardComponent>
</BoardComponent>

@code {
    [CascadingParameter]
    private HttpContext HttpContext { get; set; } = default!;

    private async Task OnSubmitAsync() {
        var user = await UserAccessor.GetRequiredUserAsync(HttpContext);
        await UserManager.SetTwoFactorEnabledAsync(user, false);
        await UserManager.ResetAuthenticatorKeyAsync(user);
        string userId = await UserManager.GetUserIdAsync(user);
        Logger.LogInformation("User with ID '{UserId}' has reset their authentication app key.", userId);

        await SignInManager.RefreshSignInAsync(user);
        RedirectManager.RedirectToWithStatus("Account/Manage/EnableAuthenticator",
            Localizer["ResetAuthenticator_Success"], HttpContext);
    }
}
