@page "/Account/ConfirmEmailChange"

@using System.Text
@using Microsoft.AspNetCore.Identity
@using Microsoft.AspNetCore.WebUtilities
@using Wave.Data

@inject UserManager<ApplicationUser> UserManager
@inject SignInManager<ApplicationUser> SignInManager
@inject IdentityRedirectManager RedirectManager
@inject IStringLocalizer<ConfirmEmailChange> Localizer

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

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

<BoardComponent CenterContent="true">
    <BoardCardComponent Heading="@Localizer["Title"]">
        <StatusMessage Message="@Message" />
    </BoardCardComponent>
</BoardComponent>
@code {
    [CascadingParameter]
    private HttpContext HttpContext { get; set; } = default!;
    [SupplyParameterFromQuery]
    private string? UserId { get; set; }
    [SupplyParameterFromQuery]
    private string? Email { get; set; }
    [SupplyParameterFromQuery]
    private string? Code { get; set; }

    private string? Message { get; set; }

    protected override async Task OnInitializedAsync() {
        if (UserId is null || Email is null || Code is null) {
            RedirectManager.RedirectToWithStatus("Account/Login", Localizer["Error_InvalidLink"], HttpContext);
        }

        var user = await UserManager.FindByIdAsync(UserId);

        if (user is null) {
            Message = Localizer["Error_UserNotFound"];
            return;
        }

        string code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(Code));
        var result = await UserManager.ChangeEmailAsync(user, Email, code);

        if (!result.Succeeded) {
            Message = Localizer["Error_ChangingMail"];
            return;
        }

        // In our UI email and username are one and the same, so when we update the email
        // we need to update the username.
        var setUserNameResult = await UserManager.SetUserNameAsync(user, Email);

        if (!setUserNameResult.Succeeded) {
            Message = Localizer["Error_ChangingUserName"];
            return;
        }

        await SignInManager.RefreshSignInAsync(user);
        Message = Localizer["Success"];
    }
}
