@page "/Account/Manage/Disable2fa"

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

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

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

<StatusMessage />
<BoardComponent>
    <BoardCardComponent Heading="@Localizer["Title"]">
        <Alert Type="Alert.MessageType.Warning" CanRemove="false">
            <strong>@Localizer["Disable2fa_Title"]</strong>
            <p>
                @Localizer["Disable2fa_Message"]
                <a href="Account/Manage/ResetAuthenticator" class="link">Reset Auth Key</a>
            </p>
        </Alert>
        <form @formname="disable-2fa" @onsubmit="OnSubmitAsync" method="post" class="w-full">
            <AntiforgeryToken />
            <button class="btn btn-error w-full mt-3" type="submit">
                @Localizer["Disable2fa_Submit"]
            </button>
        </form>
    </BoardCardComponent>
</BoardComponent>

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

    private ApplicationUser User { get; set; } = default!;

    protected override async Task OnInitializedAsync() {
        User = await UserAccessor.GetRequiredUserAsync(HttpContext);

        if (HttpMethods.IsGet(HttpContext.Request.Method) && !await UserManager.GetTwoFactorEnabledAsync(User)) {
            throw new InvalidOperationException(Localizer["Disable2fa_ErrorNotEnabled"]);
        }
    }

    private async Task OnSubmitAsync() {
        var disable2faResult = await UserManager.SetTwoFactorEnabledAsync(User, false);

        if (!disable2faResult.Succeeded) {
            throw new InvalidOperationException(Localizer["Disable2fa_ErrorUnknown"]);
        }

        string userId = await UserManager.GetUserIdAsync(User);
        Logger.LogInformation("User with ID '{UserId}' has disabled 2fa.", userId);
        RedirectManager.RedirectToWithStatus("Account/Manage/TwoFactorAuthentication",
            Localizer["Disable2fa_Success"], HttpContext);
    }
}
