@page "/Account/LoginWithRecoveryCode"

@using System.ComponentModel.DataAnnotations
@using System.Globalization
@using Microsoft.AspNetCore.Identity
@using Wave.Data

@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager
@inject IdentityRedirectManager RedirectManager
@inject ILogger<LoginWithRecoveryCode> Logger
@inject IStringLocalizer<LoginWithRecoveryCode> Localizer

<HeadContent>
    <meta name="robots" content="noindex,nofollow">
</HeadContent>

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

<StatusMessage Message="@Message" />
<BoardComponent CenterContent="true">
    <BoardCardComponent Heading="@Localizer["Title"]">
        <p class="text-justify hyphens-auto" lang="@CultureInfo.CurrentCulture">@Localizer["Message"]</p>
        <EditForm Model="Input" FormName="login-with-recovery-code" OnValidSubmit="OnValidSubmitAsync" method="post" class="w-full">
            <DataAnnotationsValidator />
            
            <InputLabelComponent LabelText="@Localizer["RecoveryCode_Label"]" For="() => Input.RecoveryCode">
                <InputText @bind-Value="Input.RecoveryCode" class="input input-bordered w-full" 
                           autocomplete="off" placeholder="@Localizer["RecoveryCode_Placeholder"]" />
            </InputLabelComponent>

            <button type="submit" class="btn btn-primary w-full">@Localizer["RecoveryCode_Submit"]</button>
        </EditForm>
    </BoardCardComponent>
</BoardComponent>

@code {
    [SupplyParameterFromForm]
    private InputModel Input { get; set; } = new();
    [SupplyParameterFromQuery]
    private string? ReturnUrl { get; set; }

    private string? Message { get; set; }
    private ApplicationUser User { get; set; } = default!;
    
    protected override async Task OnInitializedAsync() {
        // Ensure the user has gone through the username & password screen first
        User = await SignInManager.GetTwoFactorAuthenticationUserAsync() ??
            throw new InvalidOperationException("Unable to load two-factor authentication user.");
    }

    private async Task OnValidSubmitAsync() {
        string recoveryCode = Input.RecoveryCode.Replace(" ", string.Empty);
        var result = await SignInManager.TwoFactorRecoveryCodeSignInAsync(recoveryCode);

        string userId = await UserManager.GetUserIdAsync(User);
        if (result.Succeeded) {
            Logger.LogInformation("User with ID '{UserId}' logged in with a recovery code.", userId);
            RedirectManager.RedirectTo(ReturnUrl);
        } else if (result.IsLockedOut) {
            Logger.LogWarning("User account locked out.");
            RedirectManager.RedirectTo("Account/Lockout");
        } else {
            Logger.LogWarning("Invalid recovery code entered for user with ID '{UserId}' ", userId);
            Message = Localizer["RecoveryCode_ErrorInvalidCode"];
        }
    }

    private sealed class InputModel {
        [Required]
        [DataType(DataType.Text)]
        [Display(Name = "Recovery Code")]
        public string RecoveryCode { get; set; } = "";
    }
}
