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.Tasks;

[Route(Navigation.Management.Scheduler.Tasks.Details)]
public partial class Details
{
    [Parameter] public string? TaskId { 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 TaskEntity? Task { get; set; }

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

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

        Task = await Database.Task()
            .Aggregate()
            .Match(Builders<TaskEntity>.Filter.Eq(p => p.Id, TaskId))
            .FirstOrDefaultAsync(default);

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

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

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

        StateHasChanged();
    }
}