using ERPCore.Domain.Enums;

namespace ERPCore.Domain.Entities;

/// <summary>
/// One input line of a run stage — a copy of a <see cref="StageInput"/> with its
/// quantity scaled at creation, plus the live consumption/delivery figures.
/// Model: docs/30 Part C.
/// <para><b>Stock inputs</b> accumulate <see cref="ConsumedQty"/>/<see cref="ConsumedValue"/>
/// at each start and <see cref="ReturnedQty"/>/<see cref="ReturnedValue"/> on leftover
/// return or run cancel. Those four columns are the whole cost pool
/// (<c>Σ consumed − Σ returned</c>) and are deliberately <b>not</b> reset by a terminal
/// reject — already-consumed material stays in the pool (FR-MFG-16).</para>
/// <para><b>Upstream inputs</b> accumulate <see cref="DeliveredQty"/> as parent stages
/// transfer WIP in. The stage becomes Ready only when every upstream input has
/// <c>DeliveredQty &gt;= PlannedQty</c> (FR-MFG-09, an all-parents join).</para>
/// </summary>
public class RunStageInput
{
    public int RunInputId { get; set; }

    public int RunStageId { get; set; }
    public RunStage? RunStage { get; set; }

    public StageInputSource Source { get; set; }

    public int? ItemId { get; set; }
    public Item? Item { get; set; }

    /// <summary>The parent output feeding this input. This — not <see cref="RunEdge"/> — is what routes a transfer.</summary>
    public int? FromRunOutputId { get; set; }
    public RunStageOutput? FromRunOutput { get; set; }

    /// <summary>Copied from the template input: what <see cref="PlannedQty"/> is expressed in.</summary>
    public StageQtyUnit QtyUnit { get; set; } = StageQtyUnit.Pack;

    /// <summary>
    /// Scaled at creation; per-run editable until the stage starts (FR-MFG-08,
    /// <c>409 STAGE_NOT_EDITABLE</c>). Expressed in <see cref="QtyUnit"/> — so unlike the
    /// consumption figures below it is <b>not</b> necessarily a pack count.
    /// </summary>
    public decimal PlannedQty { get; set; }

    /// <summary>
    /// Stock inputs only, in the item's <b>base</b> UOM. A start consumes
    /// <c>max(0, PlannedQty − ConsumedQty)</c> and adds to these, so a rework restart
    /// with an unchanged planned quantity consumes nothing and one with a raised planned
    /// quantity consumes only the delta (FR-MFG-16).
    /// </summary>
    public decimal ConsumedQty { get; set; }
    public decimal ConsumedValue { get; set; }

    /// <summary>Upstream inputs only: accumulated by parent transfers.</summary>
    public decimal DeliveredQty { get; set; }

    /// <summary>Leftover returns (FR-MFG-14) and cancel returns (FR-MFG-17), at the consumed weighted cost.</summary>
    public decimal ReturnedQty { get; set; }
    public decimal ReturnedValue { get; set; }
}
