using System.Text.Json;
using System.Text.Json.Serialization;
using Server.Model;

namespace Server.Data
{
    public class CustomerData
    {
        #region Public Properties

        public List<Address> Customers { get; set; } = [];

        public static CustomerData Instance { get; set; } = new();

        #endregion

        
        /// <summary>
        /// Retrieves the file path for the settings JSON file.
        /// </summary>
        /// <returns>The file path of the settings JSON file as a string.</returns>
        private static string GetFilePath()
        {
            var parentDirectory = Directory.GetParent(Directory.GetCurrentDirectory());
            if (parentDirectory == null) return "Customers.json";

            return Path.Combine(parentDirectory.FullName, "Customers.json");
        }

        #region Public Method LoadAsync

        /// <summary>
        ///     Loads customer data asynchronously from a JSON file if it exists.
        /// </summary>
        /// <return>
        ///     A Task representing the asynchronous operation.
        /// </return>
        public static async Task LoadAsync()
        {
            if (!File.Exists(GetFilePath())) return;
            var jsonString = await File.ReadAllTextAsync(GetFilePath());
            var deserialized = JsonSerializer.Deserialize<CustomerData>(jsonString)!;

            Instance = deserialized;
        }

        #endregion

        #region Public Method SaveAsync

        /// <summary>
        ///     Saves the current customer data asynchronously to a JSON file.
        /// </summary>
        /// <return>
        ///     A Task representing the asynchronous operation.
        /// </return>
        public static async Task SaveAsync()
        {
            var jsonString = JsonSerializer.Serialize(Instance, new JsonSerializerOptions { WriteIndented = true, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull });
            await File.WriteAllTextAsync(GetFilePath(), jsonString);
        }

        #endregion
    }
}