using FKGees.Services;

namespace FKGees.DocsDefinitions.Decrets;

public class Zwroty : IDecretsDefinition
{
    public int DocType => 4;
    public string Type => "Zwroty";
    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("332-0-24", "WN", "[sbr]"), 
        new Definition("343-0-24", "MA", "[svr]"),
        new Definition("342-0-24", "MA", "[sbr]-[znr]")
    ];
    
    private readonly PcmService _pcmService;

    public Zwroty(PcmService pcmService)
    {
        _pcmService = pcmService;
    }

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

        var toProcess = documents
            .Where(x => x.TypDok == DocType);

        foreach (var dok in toProcess)
        {
            var opis = _pcmService.RozbNrFakturyKor(dok.DokId);
            Definitions.ForEach(d =>
            {
                var item = dok.DecretKontr();
                item.Data = dok.DataPom;
                item.DataWplywu = dok.Data;
                item.Nr = dok.NrDok;
                item.Opis = opis;
                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),
            "[sbr]" => -(doc.NettoDet + doc.PodatekDet),
            "[svr]" => -(doc.PodatekDet),
            "[sbr]-[znr]" => -(doc.NettoDet + doc.PodatekDet - doc.Netto),
            _ => 0
        };
    }
}