@page "/Account/Manage/DeletePersonalData"

@using System.ComponentModel.DataAnnotations
@using Microsoft.AspNetCore.Identity
@using MyAppName.WebApp.Components.Account
@using OpenArchival.DataAccess

@inject UserManager<ApplicationUser> UserManager
@inject SignInManager<ApplicationUser> SignInManager
@inject IdentityUserAccessor UserAccessor
@inject IdentityRedirectManager RedirectManager
@inject ILogger<DeletePersonalData> Logger

<PageTitle>Delete Personal Data</PageTitle>

<StatusMessage Message="@message" />

<h3>Delete Personal Data</h3>

<div class="alert alert-warning" role="alert">
    <p>
        <strong>Deleting this data will permanently remove your account, and this cannot be recovered.</strong>
    </p>
</div>

<div>
    <EditForm Model="Input" FormName="delete-user" OnValidSubmit="OnValidSubmitAsync" method="post">
        <DataAnnotationsValidator />
        <ValidationSummary class="text-danger" role="alert" />
        @if (requirePassword)
        {
            <div class="form-floating mb-3">
                <InputText type="password" @bind-Value="Input.Password" id="Input.Password" class="form-control" autocomplete="current-password" aria-required="true" placeholder="Please enter your password." />
                <label for="Input.Password" class="form-label">Password</label>
                <ValidationMessage For="() => Input.Password" class="text-danger" />
            </div>
        }
        <button class="w-100 btn btn-lg btn-danger" type="submit">Delete data and close my account</button>
    </EditForm>
</div>

@code {
    private string? message;
    private ApplicationUser user = default!;
    private bool requirePassword;

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

    [SupplyParameterFromForm]
    private InputModel Input { get; set; } = new();

    protected override async Task OnInitializedAsync()
    {
        Input ??= new();
        user = await UserAccessor.GetRequiredUserAsync(HttpContext);
        requirePassword = await UserManager.HasPasswordAsync(user);
    }

    private async Task OnValidSubmitAsync()
    {
        if (requirePassword && !await UserManager.CheckPasswordAsync(user, Input.Password))
        {
            message = "Error: Incorrect password.";
            return;
        }

        var result = await UserManager.DeleteAsync(user);
        if (!result.Succeeded)
        {
            throw new InvalidOperationException("Unexpected error occurred deleting user.");
        }

        await SignInManager.SignOutAsync();

        var userId = await UserManager.GetUserIdAsync(user);
        Logger.LogInformation("User with ID '{UserId}' deleted themselves.", userId);

        RedirectManager.RedirectToCurrentPage();
    }

    private sealed class InputModel
    {
        [DataType(DataType.Password)]
        public string Password { get; set; } = "";
    }
}
