using CashLineERP.Domain.Common;

namespace CashLineERP.Domain.Finance;

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

    public long BankStatementId { get; private set; }

    public int LineNumber { get; private set; }

    public DateOnly TransactionDate { get; private set; }

    public string? ExternalReference { get; private set; }

    public string? DescriptionText { get; private set; }

    public decimal DebitAmount { get; private set; }

    public decimal CreditAmount { get; private set; }

    public decimal RunningBalanceAmount { get; private set; }

    public bool IsReconciled { get; private set; }

    public long? AccountsReceivableReceiptId { get; private set; }

    public long? AccountsPayablePaymentId { get; private set; }

    public long? CustomerRefundId { get; private set; }

    public DateTime? ReconciledAtUtc { get; private set; }

    public BankStatementLine(
        long bankStatementId,
        int lineNumber,
        DateOnly transactionDate,
        string? externalReference,
        string? descriptionText,
        decimal debitAmount,
        decimal creditAmount,
        decimal runningBalanceAmount)
    {
        BankStatementId = bankStatementId;
        LineNumber = lineNumber;
        TransactionDate = transactionDate;
        ExternalReference = externalReference;
        DescriptionText = descriptionText;
        DebitAmount = debitAmount;
        CreditAmount = creditAmount;
        RunningBalanceAmount = runningBalanceAmount;
    }

    private BankStatementLine()
    {
    }

    public decimal GetStatementAmount() => CreditAmount != 0m ? CreditAmount : DebitAmount;

    public void Reconcile(long accountsReceivableReceiptId)
    {
        IsReconciled = true;
        AccountsReceivableReceiptId = accountsReceivableReceiptId;
        AccountsPayablePaymentId = null;
        CustomerRefundId = null;
        ReconciledAtUtc = DateTime.UtcNow;
    }

    public void ReconcileAccountsPayablePayment(long accountsPayablePaymentId)
    {
        IsReconciled = true;
        AccountsReceivableReceiptId = null;
        AccountsPayablePaymentId = accountsPayablePaymentId;
        CustomerRefundId = null;
        ReconciledAtUtc = DateTime.UtcNow;
    }

    public void ReconcileCustomerRefund(long customerRefundId)
    {
        IsReconciled = true;
        AccountsReceivableReceiptId = null;
        AccountsPayablePaymentId = null;
        CustomerRefundId = customerRefundId;
        ReconciledAtUtc = DateTime.UtcNow;
    }
}
