using FKGees.Services;

namespace FKGees.DocsDefinitions.Decrets;

public class KorCenZak : IDecretsDefinition
{
    public int DocType => 26;
    public string Type => "KorCenZak";
    public List<Definition> Definitions { get; } =
    [
        new Definition("361-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]")
    ];
    
    private readonly PcmService _pcmService;

    public KorCenZak(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 
                        && x.PowodKorekty().Contains(Constants.TekstPowodKorekty[nameof(KorCenZak)]));

        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,
            "[snr]-[znr]" => doc.NettoDet - doc.Netto,
            "[sbr]-[snr]" => doc.NettoDet + doc.PodatekDet - doc.Netto,
            _ => 0
        };
    }
}