namespace CashLineERP.Domain.IslamicFinance.ReceivablesFinance;

public sealed class IslamicFinanceReceivablesCaseLine
{
    public long Id { get; private set; }
    public long IslamicFinanceReceivablesCaseId { get; private set; }
    public long AccountsReceivableInvoiceId { get; private set; }
    public decimal ReceivableAmount { get; private set; }
    public decimal FinancedAmount { get; private set; }
    public string StatusCode { get; private set; } = "LINKED";
    public DateTime CreatedAtUtc { get; private set; } = DateTime.UtcNow;
    public long? CreatedByUserId { get; private set; }
    public DateTime? UpdatedAtUtc { get; private set; }
    public long? UpdatedByUserId { get; private set; }

    public IslamicFinanceReceivablesCaseLine(
        long islamicFinanceReceivablesCaseId,
        long accountsReceivableInvoiceId,
        decimal receivableAmount,
        decimal financedAmount,
        long? createdByUserId = null)
    {
        if (islamicFinanceReceivablesCaseId <= 0 || accountsReceivableInvoiceId <= 0)
        {
            throw new InvalidOperationException("Islamic Finance receivables case line requires valid case and invoice identifiers.");
        }

        if (receivableAmount <= 0m || financedAmount <= 0m)
        {
            throw new InvalidOperationException("Islamic Finance receivables case line requires positive receivable and financed amounts.");
        }

        if (financedAmount > receivableAmount)
        {
            throw new InvalidOperationException("Islamic Finance receivables case line financed amount cannot exceed linked receivable amount.");
        }

        IslamicFinanceReceivablesCaseId = islamicFinanceReceivablesCaseId;
        AccountsReceivableInvoiceId = accountsReceivableInvoiceId;
        ReceivableAmount = receivableAmount;
        FinancedAmount = financedAmount;
        CreatedByUserId = createdByUserId;
    }

    private IslamicFinanceReceivablesCaseLine()
    {
    }

    public void Activate(long actorUserId)
    {
        if (string.Equals(StatusCode, "ACTIVE", StringComparison.OrdinalIgnoreCase))
        {
            return;
        }

        StatusCode = "ACTIVE";
        UpdatedAtUtc = DateTime.UtcNow;
        UpdatedByUserId = actorUserId;
    }
}
