@page "/Account/ConfirmEmail"

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

@inject UserManager<ApplicationUser> UserManager
@inject IdentityRedirectManager RedirectManager
@inject IStringLocalizer<ConfirmEmail> Localizer


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

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

<BoardComponent CenterContent="true">
    <BoardCardComponent Heading="@Localizer["Title"]">
	    <StatusMessage Message="@Message" />
        <a class="btn btn-primary w-full mt-3" href="/Account/Login">@Localizer["Login_Label"]</a>
    </BoardCardComponent>
</BoardComponent>

@code {
    [CascadingParameter]
    private HttpContext HttpContext { get; set; } = default!;
    [SupplyParameterFromQuery]
    private string? UserId { get; set; }
    [SupplyParameterFromQuery]
    private string? Code { get; set; }

    private string? Message { get; set; }

    protected override async Task OnInitializedAsync() {
        if (UserId is null || Code is null) RedirectManager.RedirectTo("");
        
        var user = await UserManager.FindByIdAsync(UserId);
        if (user is null) {
            HttpContext.Response.StatusCode = StatusCodes.Status404NotFound;
            Message = Localizer["Error_FindingUser"];
        } else {
            string code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(Code));
            var result = await UserManager.ConfirmEmailAsync(user, code);
            Message = result.Succeeded ? Localizer["Success"] : Localizer["Error_ConfirmingEmail"];
        }
    }
}
