@page "/login"
@using System.Security.Claims
@using BlazorPolicyAuth.Data
@using BlazorPolicyAuth.Models.ViewModels
@using Microsoft.AspNetCore.Authentication
@using Microsoft.AspNetCore.Authentication.Cookies
@using Microsoft.EntityFrameworkCore
@inject AppDbContext DbContext
@inject NavigationManager NavigationManager

<div class="row">
    <div class="col-lg-4 offset-lg-4 pt-4 pb-4 border">
        <EditForm Model="Model" OnValidSubmit="Authenticate" FormName="LoginForm">
            <DataAnnotationsValidator/>
            <div class="mb-3 text-center flex-column">
                <img src="/images/login.png" style="max-height:5rem;"/>
                <h3>LOGIN</h3>
            </div>
            <div class="mb-3">
                <label>User Name</label>
                <InputText @bind-Value="Model.UserName" class="form-control" placeholder="Enter User Name"/>
                <ValidationMessage For="() => Model.UserName"></ValidationMessage>
            </div>
            <div class="mb-3">
                <label>Password</label>
                <InputText @bind-Value="Model.Password" class="form-control" placeholder="Enter Password"/>
                <ValidationMessage For="() => Model.Password"></ValidationMessage>
            </div>
            <div class="mb-3 text-center">
                <span class="text-danger">@_errorMessage</span>
            </div>
            <div class="mb-3 d-grid gap-2">
                <button class="btn btn-primary" type="submit">Login</button>
            </div>
        </EditForm>
    </div>
</div>



@code {
    [CascadingParameter]
    public HttpContext? HttpContext { get; set; }

    [SupplyParameterFromForm] 
    public LoginViewModel Model { get; set; } = new();

    private string? _errorMessage;

    private async Task Authenticate()
    {
        if(string.IsNullOrWhiteSpace(Model.UserName) || string.IsNullOrWhiteSpace(Model.Password))
        {
            _errorMessage = "Invalid User Name or Password";
            return;
        }

        var userAccount = DbContext.UserAccounts.FirstOrDefault(x => x.UserName == Model.UserName);
        if (userAccount is null || userAccount.Password != Model.Password)
        {
            _errorMessage = "Invalid User Name or Password";
            return;
        }

        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Name, Model.UserName)
        };

        /* Add Policies */
        var userAccountPolicies = await DbContext.UserAccountPolicies.Where(x => x.UserAccountId == userAccount.Id && x.IsEnabled).ToListAsync();
        claims.AddRange(userAccountPolicies.Select(userAccountPolicy => new Claim(userAccountPolicy.UserPolicy, "true")));

        var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
        var principal = new ClaimsPrincipal(identity);
        await HttpContext?.SignInAsync(principal)!;
        NavigationManager.NavigateTo("/");
    }
}