using Microsoft.EntityFrameworkCore;

namespace FKGees.Services;

public class PcmService
{
    private readonly IDbContextFactory<PcmDbContext> _dbContextFactory;

    public PcmService(IDbContextFactory<PcmDbContext> dbContextFactory)
    {
        _dbContextFactory = dbContextFactory;
    }

    public async Task<IReadOnlyList<Dok>> FetchDecretsDocuments(int[] typdok, DateTime dataOd, DateTime dataDo)
    {
        await using var context = await _dbContextFactory.CreateDbContextAsync();
        context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;

        var documents = await context.Dok
            .Include(x => x.DokKontr)
            .ThenInclude(x => x.Kontr)
            .Include(x => x.DokKasa)
            .Include(x => x.TekstDok)
            .Include(x => x.PozDok)
            .Include(x => x.RozliczaRozliczanyDok)
            .ThenInclude(x => x.Dok)
            .Include(x => x.DokKasa)
            .ThenInclude(x => x.Kasa)
            .Where(x => typdok.Contains(x.TypDok) && x.Data >= dataOd && x.Data <= dataDo)
            .ToListAsync();
        return documents;
    }

    public async Task<IReadOnlyList<Dok>> FetchRegistersDocuments(int[] typdok, DateTime dataOd, DateTime dataDo)
    {
        await using var context = await _dbContextFactory.CreateDbContextAsync();
        context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;

        var documents = await context.Dok
            .Include(x => x.DokKontr)
            .ThenInclude(x => x.Kontr)
            .Include(x => x.TekstDok)
            .Include(x => x.RozbicieDok)
            .Where(x => typdok.Contains(x.TypDok) && x.Data >= dataOd && x.Data <= dataDo)
            .ToListAsync();
        return documents;
    }

    public string WzNrFaktury(decimal dokId)
    {
        using var context = _dbContextFactory.CreateDbContext();
        context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;

        var dok = context.Rozlicza
            .Include(x => x.RozliczanyDok)
            .FirstOrDefault(x => x.DokId == dokId);

        return dok?.RozliczanyDok.NrDok ?? string.Empty;
    }

    public async Task<List<FormaPlatnosci>> FormyPlatnosci()
    {
        await using var context = await _dbContextFactory.CreateDbContextAsync();
        context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
        var fplat = await context.FormaPlatnosci.Where(x => x.FormaPlat > 4).ToListAsync();
        fplat.Add(new FormaPlatnosci{ FormaPlat = 0, Tekst = "Gotówka"});
        fplat.Add(new FormaPlatnosci{ FormaPlat = 1, Tekst = "Przelew"});
        fplat.Add(new FormaPlatnosci{ FormaPlat = 2, Tekst = "Czek potwierdzony"});
        fplat.Add(new FormaPlatnosci{ FormaPlat = 3, Tekst = "Karta płatnicza"});
        fplat.Add(new FormaPlatnosci{ FormaPlat = 4, Tekst = "Inna"});
        return fplat;
    }
}