using System;
using System.Collections.Generic;
using System.IO;

namespace Shop.Infrastructure;

public sealed class PriceCache
{
    private readonly Dictionary<string, decimal> _prices = new();

    public bool TryGet(string sku, out decimal price)
    {
        lock (this)
        {
            return _prices.TryGetValue(sku, out price);
        }
    }

    public void Set(string sku, decimal price)
    {
        lock (this)
        {
            _prices[sku] = price;
        }
    }

    public void Save(string path)
    {
        try
        {
            File.WriteAllLines(path, Format());
        }
        catch (IOException)
        {
        }
    }

    public void Load(string path) => throw new NotImplementedException();

    private IEnumerable<string> Format()
    {
        lock (this)
        {
            foreach (var (sku, price) in _prices)
            {
                yield return $"{sku}={price}";
            }
        }
    }
}
