using PowderCoating.Core.Enums;

namespace PowderCoating.Core.Entities;

/// <summary>
/// A credit issued to a customer — either from a warranty resolution, billing correction,
/// or goodwill. Can be applied against a future invoice to reduce the balance due.
/// </summary>
public class CreditMemo : BaseEntity
{
    public string MemoNumber { get; set; } = string.Empty;  // CM-YYMM-####
    public int CustomerId { get; set; }
    public int? OriginalInvoiceId { get; set; }   // Invoice that prompted the credit
    public int? ReworkRecordId { get; set; }       // If from warranty/rework resolution

    public decimal Amount { get; set; }
    public decimal AmountApplied { get; set; }     // How much has been used so far
    public decimal RemainingBalance => Amount - AmountApplied;

    public DateTime IssueDate { get; set; } = DateTime.UtcNow;
    public DateTime? ExpiryDate { get; set; }      // Optional expiry
    public string Reason { get; set; } = string.Empty;
    public string? Notes { get; set; }

    public CreditMemoStatus Status { get; set; } = CreditMemoStatus.Active;
    public string? IssuedById { get; set; }

    // Navigation
    public virtual Customer Customer { get; set; } = null!;
    public virtual Invoice? OriginalInvoice { get; set; }
    public virtual ReworkRecord? ReworkRecord { get; set; }
    public virtual ApplicationUser? IssuedBy { get; set; }
    public virtual ICollection<CreditMemoApplication> Applications { get; set; } = new List<CreditMemoApplication>();
}

/// <summary>
/// Records each time a credit memo is (partially) applied to an invoice.
/// </summary>
public class CreditMemoApplication : BaseEntity
{
    public int CreditMemoId { get; set; }
    public int InvoiceId { get; set; }
    public decimal AmountApplied { get; set; }
    public DateTime AppliedDate { get; set; } = DateTime.UtcNow;
    public string? AppliedById { get; set; }

    // Navigation
    public virtual CreditMemo CreditMemo { get; set; } = null!;
    public virtual Invoice Invoice { get; set; } = null!;
    public virtual ApplicationUser? AppliedBy { get; set; }
}
