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

namespace CashLineERP.Domain.Inventory;

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

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

    public long BranchId { get; private set; }

    public long WarehouseId { get; private set; }

    public DateOnly CountDate { get; private set; }

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

    public string? Notes { get; private set; }

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

    public decimal TotalVarianceAmount { get; private set; }

    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 long? InventoryAdjustmentId { get; private set; }

    public long? GeneralLedgerBatchId { get; private set; }

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

    public StockCount(
        string countNumber,
        long branchId,
        long warehouseId,
        DateOnly countDate,
        string countTypeCode,
        string? notes)
    {
        CountNumber = countNumber;
        BranchId = branchId;
        WarehouseId = warehouseId;
        CountDate = countDate;
        CountTypeCode = countTypeCode;
        Notes = notes;
    }

    private StockCount()
    {
    }

    public void AddLine(
        int lineNumber,
        long itemId,
        long? warehouseLocationId,
        decimal bookQuantity,
        decimal countedQuantity,
        string unitOfMeasureCode,
        decimal unitCost,
        string stockStatus,
        string? batchNumber,
        string? serialNumber,
        string? notes)
    {
        if (bookQuantity < 0m)
        {
            throw new InvalidOperationException("Stock count book quantity cannot be negative.");
        }

        if (countedQuantity < 0m)
        {
            throw new InvalidOperationException("Stock count counted quantity cannot be negative.");
        }

        if (unitCost < 0m)
        {
            throw new InvalidOperationException("Stock count unit cost cannot be negative.");
        }

        Lines.Add(new StockCountLine(
            stockCountId: Id,
            lineNumber: lineNumber,
            itemId: itemId,
            warehouseLocationId: warehouseLocationId,
            bookQuantity: bookQuantity,
            countedQuantity: countedQuantity,
            unitOfMeasureCode: unitOfMeasureCode,
            unitCost: unitCost,
            stockStatus: stockStatus,
            batchNumber: batchNumber,
            serialNumber: serialNumber,
            notes: notes));

        RecalculateTotals();
    }

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

        if (Lines.Count == 0)
        {
            throw new InvalidOperationException("Stock count must contain at least one line before submission.");
        }

        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 stock counts can be approved.");
        }

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

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

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

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

        StatusId = WorkflowStatusSeedIds.Posted;
        InventoryAdjustmentId = inventoryAdjustmentId;
        GeneralLedgerBatchId = generalLedgerBatchId;
        PostedAtUtc = DateTime.UtcNow;
        PostedByUserId = actorUserId;
        Touch(actorUserId);
    }

    private void RecalculateTotals()
    {
        TotalVarianceAmount = Lines.Sum(line => line.VarianceAmount);
    }
}
