using CashLineERP.Domain.Common;

namespace CashLineERP.Domain.Finance;

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

    public long SupplierStatementId { get; private set; }

    public DateTime DeliveredAtUtc { get; private set; }

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

    public string? RecipientAddress { get; private set; }

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

    public string? Notes { get; private set; }

    public string? AcknowledgmentStatusCode { get; private set; }

    public DateTime? AcknowledgedAtUtc { get; private set; }

    public long? AcknowledgedByUserId { get; private set; }

    public SupplierStatementDeliveryLog(
        long supplierStatementId,
        DateTime deliveredAtUtc,
        string channelCode,
        string? recipientAddress,
        string deliveryStatusCode,
        string? notes,
        long actorUserId)
    {
        if (string.IsNullOrWhiteSpace(channelCode))
        {
            throw new InvalidOperationException("Supplier statement delivery channel is required.");
        }

        if (string.IsNullOrWhiteSpace(deliveryStatusCode))
        {
            throw new InvalidOperationException("Supplier statement delivery status is required.");
        }

        SupplierStatementId = supplierStatementId;
        DeliveredAtUtc = deliveredAtUtc;
        ChannelCode = channelCode.Trim().ToUpperInvariant();
        RecipientAddress = string.IsNullOrWhiteSpace(recipientAddress) ? null : recipientAddress.Trim();
        DeliveryStatusCode = deliveryStatusCode.Trim().ToUpperInvariant();
        Notes = string.IsNullOrWhiteSpace(notes) ? null : notes.Trim();
        CreatedByUserId = actorUserId;
    }

    private SupplierStatementDeliveryLog()
    {
    }

    public void Acknowledge(long actorUserId, string acknowledgmentStatusCode, string? notes)
    {
        if (string.IsNullOrWhiteSpace(acknowledgmentStatusCode))
        {
            throw new InvalidOperationException("Supplier statement acknowledgment status is required.");
        }

        AcknowledgmentStatusCode = acknowledgmentStatusCode.Trim().ToUpperInvariant();
        AcknowledgedAtUtc = DateTime.UtcNow;
        AcknowledgedByUserId = actorUserId;
        if (!string.IsNullOrWhiteSpace(notes))
        {
            Notes = notes.Trim();
        }

        Touch(actorUserId);
    }
}
