using System.Text.Json;

namespace Elfisa.Core;

public sealed class DraftItem
{
    public string SupplierPriceId { get; set; } = "";
    public string Name { get; set; } = "";
    public string Supplier { get; set; } = "";
    public string? Barcode { get; set; }
    public decimal Price { get; set; }
    public decimal Qty { get; set; } = 1;
    public decimal LineSum => Price * Qty;
}

public sealed class DraftOrder
{
    public string Id { get; set; } = Guid.NewGuid().ToString();
    public string Number { get; set; } = "";
    public DateTime CreatedAt { get; set; } = DateTime.Now;
    public string? LocationId { get; set; }
    public string? LocationAddress { get; set; }
    public string? Comment { get; set; }
    public List<DraftItem> Items { get; set; } = new();
    public decimal Total => Items.Sum(i => i.LineSum);
    public int ItemsCount => Items.Count;
}

/// <summary>Локальные черновики заказов (%APPDATA%\ElfisaAvalonia\drafts.json).</summary>
public static class DraftStore
{
    private sealed class Box { public List<DraftOrder> Drafts { get; set; } = new(); }

    private static readonly string Dir =
        Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ElfisaAvalonia");
    private static readonly string File = Path.Combine(Dir, "drafts.json");

    private static Box _box = Load();

    public static IReadOnlyList<DraftOrder> All => _box.Drafts;

    private static Box Load()
    {
        try
        {
            if (System.IO.File.Exists(File))
                return JsonSerializer.Deserialize<Box>(System.IO.File.ReadAllText(File)) ?? new Box();
        }
        catch { }
        return new Box();
    }

    private static void Save()
    {
        try
        {
            Directory.CreateDirectory(Dir);
            System.IO.File.WriteAllText(File, JsonSerializer.Serialize(_box, new JsonSerializerOptions { WriteIndented = true }));
        }
        catch { }
    }

    public static DraftOrder Add(DraftOrder draft)
    {
        _box.Drafts.Insert(0, draft);
        Save();
        return draft;
    }

    public static void Remove(string id)
    {
        _box.Drafts.RemoveAll(d => d.Id == id);
        Save();
    }
}
