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

namespace CashLineERP.Domain.Finance;

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

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

    public long SupplierId { get; private set; }

    public DateOnly PaymentDate { get; private set; }

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

    public string CurrencyCode { get; private set; } = "EGP";

    public decimal AmountAmount { get; private set; }

    public decimal UnappliedAmount { get; private set; }

    public string? ReferenceNumber { get; private set; }

    public string? Notes { get; private set; }

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

    public DateTime? SubmittedAtUtc { get; private set; }

    public long? SubmittedByUserId { get; private set; }

    public DateTime? ApprovedAtUtc { get; private set; }

    public long? ApprovedByUserId { get; private set; }

    public DateTime? PostedAtUtc { get; private set; }

    public long? PostedByUserId { get; private set; }

    public DateOnly? ReversalDate { get; private set; }

    public DateTime? ReversedAtUtc { get; private set; }

    public long? ReversedByUserId { get; private set; }

    public string? ReversalReasonCode { get; private set; }

    public string? ReversalNotes { get; private set; }

    public long? ReversalGeneralLedgerBatchId { get; private set; }

    public long? RepostedFromPaymentId { get; private set; }

    public long? RepostPaymentId { get; private set; }

    public long? GeneralLedgerBatchId { get; private set; }

    public List<AccountsPayablePaymentAllocation> Allocations { get; private set; } = [];

    public AccountsPayablePayment(
        string paymentNumber,
        long supplierId,
        DateOnly paymentDate,
        string paymentMethod,
        string currencyCode,
        decimal amountAmount,
        string? referenceNumber,
        string? notes)
    {
        PaymentNumber = paymentNumber;
        SupplierId = supplierId;
        PaymentDate = paymentDate;
        PaymentMethod = paymentMethod;
        CurrencyCode = currencyCode;
        AmountAmount = amountAmount;
        UnappliedAmount = amountAmount;
        ReferenceNumber = referenceNumber;
        Notes = notes;
    }

    private AccountsPayablePayment()
    {
    }

    public void AddAllocation(long accountsPayableBillId, decimal allocationAmount, DateOnly allocationDate)
    {
        if (allocationAmount <= 0m)
        {
            throw new InvalidOperationException("AP payment allocation amount must be greater than zero.");
        }

        Allocations.Add(new AccountsPayablePaymentAllocation(
            accountsPayablePaymentId: Id,
            accountsPayableBillId: accountsPayableBillId,
            allocationAmount: allocationAmount,
            allocationDate: allocationDate));

        UnappliedAmount = AmountAmount - Allocations.Sum(entry => entry.AllocationAmount);

        if (UnappliedAmount < 0m)
        {
            throw new InvalidOperationException("AP payment allocations cannot exceed payment amount.");
        }
    }

    public void Submit(long actorUserId)
    {
        if (StatusId != WorkflowStatusSeedIds.Draft && StatusId != WorkflowStatusSeedIds.Returned)
        {
            throw new InvalidOperationException("Only draft or returned AP payments can be submitted.");
        }

        StatusId = WorkflowStatusSeedIds.Submitted;
        SubmittedAtUtc = DateTime.UtcNow;
        SubmittedByUserId = actorUserId;
        Touch(actorUserId);
    }

    public void Approve(long actorUserId)
    {
        if (StatusId == WorkflowStatusSeedIds.Approved)
        {
            return;
        }

        if (StatusId != WorkflowStatusSeedIds.Submitted)
        {
            throw new InvalidOperationException("Only submitted AP payments can be approved.");
        }

        if (SubmittedByUserId == actorUserId)
        {
            throw new InvalidOperationException("AP payment maker-checker control prohibits self-approval.");
        }

        StatusId = WorkflowStatusSeedIds.Approved;
        ApprovedAtUtc = DateTime.UtcNow;
        ApprovedByUserId = actorUserId;
        Touch(actorUserId);
    }

    public void Post(long actorUserId, long generalLedgerBatchId)
    {
        if (StatusId == WorkflowStatusSeedIds.Posted)
        {
            GeneralLedgerBatchId ??= generalLedgerBatchId;
            return;
        }

        if (StatusId != WorkflowStatusSeedIds.Approved)
        {
            throw new InvalidOperationException("AP payment must be approved before posting.");
        }

        StatusId = WorkflowStatusSeedIds.Posted;
        GeneralLedgerBatchId = generalLedgerBatchId;
        UnappliedAmount = AmountAmount - Allocations.Sum(entry => entry.AllocationAmount);
        PostedAtUtc = DateTime.UtcNow;
        PostedByUserId = actorUserId;
        Touch(actorUserId);
    }

    public void Reverse(long actorUserId, DateOnly reversalDate, string reasonCode, string? notes, long reversalGeneralLedgerBatchId)
    {
        if (StatusId != WorkflowStatusSeedIds.Posted)
        {
            throw new InvalidOperationException("Only posted AP payments can be reversed.");
        }

        StatusId = WorkflowStatusSeedIds.Reversed;
        ReversalDate = reversalDate;
        ReversedAtUtc = DateTime.UtcNow;
        ReversedByUserId = actorUserId;
        ReversalReasonCode = reasonCode;
        ReversalNotes = notes;
        ReversalGeneralLedgerBatchId = reversalGeneralLedgerBatchId;
        Touch(actorUserId);
    }

    public void MarkAsRepost(long sourcePaymentId, long actorUserId)
    {
        RepostedFromPaymentId = sourcePaymentId;
        Touch(actorUserId);
    }

    public void LinkRepostPayment(long replacementPaymentId, long actorUserId)
    {
        if (StatusId != WorkflowStatusSeedIds.Reversed)
        {
            throw new InvalidOperationException("Only reversed AP payments can link to a replacement payment.");
        }

        if (RepostPaymentId.HasValue)
        {
            throw new InvalidOperationException("AP payment already has a linked replacement payment.");
        }

        RepostPaymentId = replacementPaymentId;
        Touch(actorUserId);
    }
}
