using CashLineERP.Domain.Common;
using CashLineERP.SharedKernel.Workflow;

namespace CashLineERP.Domain.Finance;

public sealed class GeneralLedgerJournal : Entity
{
    public long Id { get; private set; }

    public long GeneralLedgerBatchId { get; private set; }

    public string JournalNumber { get; private set; } = string.Empty;

    public string JournalType { get; private set; } = string.Empty;

    public DateOnly PostingDate { get; private set; }

    public DateOnly? TaxDate { get; private set; }

    public DateOnly? DocumentDate { get; private set; }

    public long StatusId { get; private set; } = WorkflowStatusSeedIds.Posted;

    public string? DescriptionText { get; private set; }

    public decimal TotalAmount { get; private set; }

    public List<GeneralLedgerJournalLine> Lines { get; private set; } = [];

    public GeneralLedgerJournal(
        long generalLedgerBatchId,
        string journalNumber,
        string journalType,
        DateOnly postingDate,
        DateOnly? taxDate,
        DateOnly? documentDate,
        string? descriptionText)
    {
        GeneralLedgerBatchId = generalLedgerBatchId;
        JournalNumber = journalNumber;
        JournalType = journalType;
        PostingDate = postingDate;
        TaxDate = taxDate;
        DocumentDate = documentDate;
        DescriptionText = descriptionText;
    }

    private GeneralLedgerJournal()
    {
    }

    public void AddLine(
        int lineNumber,
        long generalLedgerAccountId,
        long? branchId,
        long? departmentId,
        long? partyId,
        long? itemId,
        decimal debitAmount,
        decimal creditAmount,
        string? currencyCode,
        decimal fxRate,
        string? lineDescription)
    {
        Lines.Add(new GeneralLedgerJournalLine(
            generalLedgerJournalId: Id,
            lineNumber: lineNumber,
            generalLedgerAccountId: generalLedgerAccountId,
            branchId: branchId,
            departmentId: departmentId,
            partyId: partyId,
            itemId: itemId,
            debitAmount: debitAmount,
            creditAmount: creditAmount,
            currencyCode: currencyCode,
            fxRate: fxRate,
            lineDescription: lineDescription));

        TotalAmount = Lines.Sum(line => Math.Max(line.DebitAmount, line.CreditAmount));
    }
}
