using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Http;

namespace Guestlist.Components.Pages;

public partial class GuestList : ComponentBase
{
    [Inject]
    protected GuestEntryService GuestEntryService { get; set; } = default!;

    [Inject]
    protected IHttpContextAccessor HttpContextAccessor { get; set; } = default!;

    [Inject]
    protected AuthenticationStateProvider AuthenticationStateProvider { get; set; } = default!;

    [Inject]
    protected NavigationManager Navigation { get; set; } = default!;

    protected List<GuestEntryDocument>? GuestEntries { get; set; }
    protected bool ShowLeaveGuestList { get; set; }

    protected override async Task OnInitializedAsync()
    {
        var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
        var user = authState.User;
        var isStaffUser =
            user.Identity?.IsAuthenticated == true &&
            (user.IsInRole(UserRoles.Admin) || user.IsInRole(UserRoles.Maintainer));

        var hasGuestAccess =
            HttpContextAccessor.HttpContext?.Session.GetString("GuestAccessGranted") == "true";

        if (!isStaffUser && !hasGuestAccess)
        {
            Navigation.NavigateTo("/guest");
            return;
        }

        ShowLeaveGuestList = !isStaffUser && hasGuestAccess;
        GuestEntries = await GuestEntryService.GetAllAsync();
    }
}
