using Microsoft.AspNetCore.Components;
using Server.Data;
using Server.Model;

namespace Server.Components.Pages
{
    public partial class CreatePage
    {
        #region Dependencies

        [Inject]
        private NavigationManager NavigationManager { get; set; } = null!;

        #endregion

        #region Private Properties

        private string? AlertMessage { get; set; }
        private string? InvoiceId { get; set; }

        #endregion

        #region Override SetParametersAsync

        /// <inheritdoc />
        public override async Task SetParametersAsync(ParameterView parameters)
        {
            parameters.SetParameterProperties(this);

            await SettingsData.LoadAsync();

            await base.SetParametersAsync(ParameterView.Empty);
        }

        #endregion

        #region Private Method CreateInvoiceAsync

        /// <summary>
        ///     Asynchronously creates a new invoice if the provided InvoiceId is not null, empty,
        ///     or whitespace, and does not already exist in the system. If the invoice is created
        ///     successfully, navigates to the newly created invoice page.
        /// </summary>
        /// <returns>
        ///     A Task representing the asynchronous operation.
        /// </returns>
        private async Task CreateInvoiceAsync()
        {
            if (string.IsNullOrWhiteSpace(InvoiceId)) return;
            if (await InvoiceData.ExistsAsync(InvoiceId))
            {
                AlertMessage = "Eine Rechnung mit der Rechnungsnummer existiert bereits";
                return;
            }

            var invoice = new InvoiceModel
            {
                InvoiceId = InvoiceId,
                Comment = SettingsData.Instance.Comment,
                PaymentData = SettingsData.Instance.PaymentData,
                Seller = SettingsData.Instance.SellerAddress
            };

            await InvoiceData.SaveAsync(invoice);

            NavigationManager.NavigateTo($"/edit/{InvoiceId}");
        }

        #endregion
    }
}