using Insight.Infrastructure;
using Insight.Infrastructure.Entities;
using Insight.Web.Constants;
using Microsoft.AspNetCore.Components;
using MongoDB.Bson;
using MongoDB.Driver;
using MudBlazor;

namespace Insight.Web.Pages.Management.Customers;

[Route(Navigation.Management.Customers.Details)]
public partial class Details
{
    [Parameter] public string? CustomerId { get; set; }

    [Inject] private IMongoDatabase Database { get; init; } = default!;
    [Inject] private ISnackbar Snackbar { get; init; } = default!;
    [Inject] private NavigationManager NavigationManager { get; init; } = default!;

    private string Title { get; set; } = Global.Name;
    private List<BreadcrumbItem> Breadcrumbs { get; } = new();
    private CustomerEntity? Customer { get; set; }

    private async Task LoadDataAsync()
    {
        Breadcrumbs.Clear();
        Customer = null;

        if (string.IsNullOrWhiteSpace(CustomerId) || ObjectId.TryParse(CustomerId, out var customerId) is false)
        {
            Notification.Error(Snackbar, "Not Found");
            NavigationManager.NavigateTo(Navigation.Management.Customers.Index);
            return;
        }

        Breadcrumbs.Add(new BreadcrumbItem("Home", href: Navigation.Home));
        Breadcrumbs.Add(new BreadcrumbItem("Customers", href: Navigation.Management.Customers.Index));

        StateHasChanged();

        Customer = await Database.Customer()
            .Aggregate()
            .Match(Builders<CustomerEntity>.Filter.Eq(p => p.Id, CustomerId))
            .Lookup<CustomerEntity, HostEntity, CustomerEntity>(Database.Host(), p => p.Id, p => p.Customer, p => p.Hosts)
            .FirstOrDefaultAsync(default);

        if (Customer is null)
        {
            Notification.Error(Snackbar, "Not Found");
            NavigationManager.NavigateTo(Navigation.Management.Customers.Index);
            return;
        }

        Title = $"Customer » {Customer.Name}｜Insight";
        Breadcrumbs.Add(new BreadcrumbItem(Customer.Name, href: "#", true));

        StateHasChanged();
    }
}