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

namespace Insight.Web.Pages.Management.Customers;

public partial class CustomerCreateDialog
{
    [Parameter] public EventCallback OnChanges { get; set; }

    [Inject] private IMongoDatabase Database { get; init; } = default!;
    [Inject] private ISnackbar Snackbar { get; init; } = default!;
    [Inject] private ILogger<CustomerCreateDialog> Logger { get; init; } = default!;

    private CustomerEntity? Customer { get; set; } = new();

    private async Task SubmitAsync()
    {
        if (Customer is null) return;
        Customer.Insert = DateTime.Now;

        try
        {
            await Database.Customer()
                .InsertOneAsync(Customer, cancellationToken: default)
                .ConfigureAwait(false);

            Notification.Success(Snackbar);

            if (OnChanges.HasDelegate)
            {
                await InvokeAsync(async () =>
                {
                    await OnChanges.InvokeAsync(this);
                });
            }
        }
        catch (Exception ex)
        {
            Notification.Error(Snackbar);
            Logger.LogError(ex.ToString());
        }
        finally
        {
            Customer = new();
            _visible = false;
        }
    }
}