@page "/Account/RegisterConfirmation"

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

@inject UserManager<ApplicationUser> UserManager
@inject IEmailSender<ApplicationUser> EmailSender
@inject NavigationManager NavigationManager
@inject IdentityRedirectManager RedirectManager
@inject IStringLocalizer<RegisterConfirmation> Localizer

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

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

<StatusMessage Message="@statusMessage"/>

<BoardComponent CenterContent="true">
	<BoardCardComponent Heading="@Localizer["Title"]">
		<Alert CanRemove="false" Type="Alert.MessageType.Success">
			@if (emailConfirmationLink is not null) {
				<p>
					This app does not currently have a real email sender registered, see <a href="https://aka.ms/aspaccountconf">these docs</a> for how to configure a real email sender.
					Normally this would be emailed: <a href="@emailConfirmationLink">Click here to confirm your account</a>
				</p>
			} else {
				<p>@Localizer["Message"]</p>
			}
		</Alert>
	</BoardCardComponent>
</BoardComponent>

@code {
	private string? emailConfirmationLink;
	private string? statusMessage;

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

	[SupplyParameterFromQuery] private string? Email { get; set; }

	[SupplyParameterFromQuery] private string? ReturnUrl { get; set; }

	protected override async Task OnInitializedAsync() {
		if (Email is null) {
			RedirectManager.RedirectTo("");
		}

		var user = await UserManager.FindByEmailAsync(Email);
		if (user is null) {
			HttpContext.Response.StatusCode = StatusCodes.Status404NotFound;
			statusMessage = "Error finding user for unspecified email";
		} else if (EmailSender is IdentityNoOpEmailSender) {
			// Once you add a real email sender, you should remove this code that lets you confirm the account
			var userId = await UserManager.GetUserIdAsync(user);
			var code = await UserManager.GenerateEmailConfirmationTokenAsync(user);
			code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
			emailConfirmationLink = NavigationManager.GetUriWithQueryParameters(
				NavigationManager.ToAbsoluteUri("Account/ConfirmEmail").AbsoluteUri,
				new Dictionary<string, object?> {["userId"] = userId, ["code"] = code, ["returnUrl"] = ReturnUrl});
		}
	}

}