using System.Text.Json;
using KiMailOrderAgent.Models;

namespace KiMailOrderAgent.Storage;

public class PendingOrderStore
{
    private readonly string _filePath = "pending_orders.json";

    public List<ExtractedOrder> Load()
    {
        if (!File.Exists(_filePath))
            return new List<ExtractedOrder>();

        var json = File.ReadAllText(_filePath);

        return JsonSerializer.Deserialize<List<ExtractedOrder>>(json)
               ?? new List<ExtractedOrder>();
    }

    public void Save(List<ExtractedOrder> orders)
    {
        var json = JsonSerializer.Serialize(orders, new JsonSerializerOptions
        {
            WriteIndented = true
        });

        File.WriteAllText(_filePath, json);
    }

    public ExtractedOrder? FindById(string orderId)
    {
        return Load().FirstOrDefault(x => x.Id == orderId);
    }

    public void Update(ExtractedOrder order)
    {
        var orders = Load();

        var index = orders.FindIndex(x => x.Id == order.Id);

        if (index >= 0)
            orders[index] = order;
        else
            orders.Add(order);

        Save(orders);
    }
}