using CartWise.Domain.Enums;

namespace CartWise.Domain.Entities;

public class ShoppingListItem
{
    public Guid ShoppingListItemId { get; private set; }

    public Guid ShoppingListId { get; private set; }

    public Guid? GroceryConceptId { get; private set; }

    public string DisplayName { get; private set; } = null!;

    public decimal? Quantity { get; private set; }

    public string? Unit { get; private set; }

    public ShoppingListItemStatus Status { get; private set; }

    public int SortOrder { get; private set; }

    public string AddedByUserId { get; private set; } = null!;

    public DateTime AddedUtc { get; private set; }

    public DateTime? PurchasedUtc { get; private set; }

    public string? Notes { get; private set; }

    public Guid RowVersion { get; private set; }

    private ShoppingListItem()
    {
    }

    internal ShoppingListItem(
        Guid shoppingListId,
        string displayName,
        decimal? quantity,
        string? unit,
        int sortOrder,
        string addedByUserId,
        DateTime addedUtc)
    {
        if (shoppingListId == Guid.Empty)
        {
            throw new ArgumentException("ShoppingListId is required.", nameof(shoppingListId));
        }

        if (string.IsNullOrWhiteSpace(displayName))
        {
            throw new ArgumentException("DisplayName is required.", nameof(displayName));
        }

        if (string.IsNullOrWhiteSpace(addedByUserId))
        {
            throw new ArgumentException("AddedByUserId is required.", nameof(addedByUserId));
        }

        ShoppingListItemId = Guid.NewGuid();
        ShoppingListId = shoppingListId;
        DisplayName = displayName.Trim();
        Quantity = quantity;
        Unit = unit;
        Status = ShoppingListItemStatus.Needed;
        SortOrder = sortOrder;
        AddedByUserId = addedByUserId;
        AddedUtc = addedUtc;
        RowVersion = Guid.NewGuid();
    }

    public void TogglePurchased(DateTime utcNow)
    {
        if (Status == ShoppingListItemStatus.Purchased)
        {
            Status = ShoppingListItemStatus.Needed;
            PurchasedUtc = null;
        }
        else
        {
            Status = ShoppingListItemStatus.Purchased;
            PurchasedUtc = utcNow;
        }

        RowVersion = Guid.NewGuid();
    }

    public void ToggleSkipped()
    {
        Status = Status == ShoppingListItemStatus.Skipped
            ? ShoppingListItemStatus.Needed
            : ShoppingListItemStatus.Skipped;

        RowVersion = Guid.NewGuid();
    }
}
