namespace FKGees.DocsDefinitions.Decrets;

public class PzFaktura : IDecretsDefinition
{
    public int DocType => 2;
    public string Type => "PzFaktura";
    public List<Definition> Definitions { get; } =
    [
        new Definition("301-0-24", "WN", "[znr]"), 
        new Definition("221-0-24", "WN", "[zvr]"), 
        new Definition("210-1", "MA", "[zbr]"),
        new Definition("301-0-24", "MA", "[znr]"), 
        new Definition("342-0-24", "MA", "[snr]-[znr]"),
        new Definition("343-0-24", "MA", "[sbr]-[snr]"), 
        new Definition("332-0-24", "WN", "[sbr]")
    ];

    public Task<List<DecretsResult>> Process(IReadOnlyList<Dok> documents)
    {
        var result = new List<DecretsResult>();

        var toProcess = documents
            .Where(x => x.TypDok == DocType && x.RozliczaRozliczanyDok.Count == 1);

        foreach (var dok in toProcess)
        {
            Definitions.ForEach(d =>
            {
                var item = dok.DecretKontr();
                item.Data = dok.Data;
                item.DataWplywu = dok.RozliczaRozliczanyDok.FirstOrDefault()
                    ?.Dok.Data ?? null;
                item.Nr = dok.NrDok;
                item.Opis = dok.RozliczaRozliczanyDok.FirstOrDefault()?.Dok.NrDok ?? string.Empty;
                item.StronaKonta = d.AccountSide;
                item.KontoFk = d.Account;
                item.Kwota = ProcessValue(dok, d.Expression).AsString();

                result.Add(item);
            });
        }

        return Task.FromResult(result);
    }

    private static decimal ProcessValue(Dok doc, string expression)
    {
        return expression switch
        {
            "[znr]" => doc.Netto,
            "[zvr]" => doc.Podatek,
            "[zbr]" => doc.Netto + doc.Podatek,
            "[snr]-[znr]" => doc.NettoDet - doc.Netto,
            "[sbr]-[snr]" => doc.PodatekDet,
            "[sbr]" => doc.NettoDet + doc.PodatekDet,
            _ => 0
        };
    }
}