using CashLineERP.Application.Finance;
using CashLineERP.SharedKernel.Workflow;
using Microsoft.EntityFrameworkCore;

namespace CashLineERP.Infrastructure.Persistence.Repositories;

public sealed class GeneralLedgerReadRepository : IGeneralLedgerReadRepository
{
    private readonly CashLineErpDbContext _dbContext;

    public GeneralLedgerReadRepository(CashLineErpDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public IReadOnlyCollection<GeneralLedgerBatchView> GetGeneralLedgerBatches()
    {
        return _dbContext.GeneralLedgerBatches
            .AsNoTracking()
            .Include(batch => batch.Journals)
            .ThenInclude(journal => journal.Lines)
            .OrderByDescending(batch => batch.Id)
            .ToArray()
            .Select(batch => new GeneralLedgerBatchView(
                batch.Id,
                batch.BatchNumber,
                batch.BatchType,
                batch.BranchId,
                batch.PeriodId,
                WorkflowStatusSeedIds.ToCode(batch.StatusId),
                batch.DescriptionText,
                batch.SourceModule,
                batch.SourceDocumentId,
                batch.BatchTotalAmount,
                batch.Journals.OrderBy(journal => journal.Id).Select(journal => new GeneralLedgerJournalView(
                    journal.Id,
                    journal.JournalNumber,
                    journal.JournalType,
                    journal.PostingDate,
                    WorkflowStatusSeedIds.ToCode(journal.StatusId),
                    journal.DescriptionText,
                    journal.TotalAmount,
                    journal.Lines.OrderBy(line => line.LineNumber).Select(line => new GeneralLedgerJournalLineView(
                        line.Id,
                        line.LineNumber,
                        line.GeneralLedgerAccountId,
                        line.BranchId,
                        line.PartyId,
                        line.ItemId,
                        line.DebitAmount,
                        line.CreditAmount,
                        line.CurrencyCode,
                        line.FxRate,
                        line.LineDescription)).ToArray())).ToArray()))
            .ToArray();
    }
}
