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.Scheduler.Triggers;

[Route(Navigation.Management.Scheduler.Triggers.Details)]
public partial class Details
{
    [Parameter] public string? TriggerId { 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 TriggerEntity? Trigger { get; set; }

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

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

        Trigger = await Database.Trigger()
            .Aggregate()
            .Match(Builders<TriggerEntity>.Filter.Eq(p => p.Id, TriggerId))
            .FirstOrDefaultAsync(default);

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

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

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

        StateHasChanged();
    }
}