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

namespace CashLineERP.Domain.Procurement;

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

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

    public long BranchId { get; private set; }

    public long RequesterUserId { get; private set; }

    public DateOnly RequisitionDate { get; private set; }

    public DateOnly? NeedByDate { get; private set; }

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

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

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

    public decimal EstimatedTotalAmount { get; private set; }

    public List<PurchaseRequisitionLine> Lines { get; private set; } = [];

    public PurchaseRequisition(
        string requisitionNumber,
        long branchId,
        long requesterUserId,
        DateOnly requisitionDate,
        DateOnly? needByDate,
        string purposeText,
        string currencyCode = "EGP")
    {
        RequisitionNumber = requisitionNumber;
        BranchId = branchId;
        RequesterUserId = requesterUserId;
        RequisitionDate = requisitionDate;
        NeedByDate = needByDate;
        PurposeText = purposeText;
        CurrencyCode = currencyCode;
    }

    private PurchaseRequisition()
    {
    }

    public void AddLine(
        int lineNumber,
        long itemId,
        decimal requestedQuantity,
        string unitOfMeasureCode,
        decimal? estimatedUnitPrice,
        DateOnly? needByDate,
        string? notes)
    {
        var line = new PurchaseRequisitionLine(
            requisitionId: Id,
            lineNumber: lineNumber,
            itemId: itemId,
            requestedQuantity: requestedQuantity,
            unitOfMeasureCode: unitOfMeasureCode,
            estimatedUnitPrice: estimatedUnitPrice,
            needByDate: needByDate,
            notes: notes);

        Lines.Add(line);
        RecalculateTotal();
    }

    public void Submit(long actorUserId)
    {
        StatusId = WorkflowStatusSeedIds.Submitted;
        Touch(actorUserId);
    }

    private void RecalculateTotal()
    {
        EstimatedTotalAmount = Lines.Sum(line => line.RequestedQuantity * (line.EstimatedUnitPrice ?? 0m));
    }
}
