using CartWise.Domain.Enums;

namespace CartWise.Domain.Entities;

public class ShoppingList
{
    private readonly List<ShoppingListItem> _items = [];

    public Guid ShoppingListId { get; private set; }

    public Guid HouseholdId { get; private set; }

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

    public ShoppingListStatus Status { get; private set; }

    public DateTime CreatedUtc { get; private set; }

    public DateTime? CompletedUtc { get; private set; }

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

    public IReadOnlyCollection<ShoppingListItem> Items => _items.AsReadOnly();

    private ShoppingList()
    {
    }

    public ShoppingList(Guid householdId, string name, string createdByUserId, DateTime createdUtc)
    {
        if (householdId == Guid.Empty)
        {
            throw new ArgumentException("HouseholdId is required.", nameof(householdId));
        }

        if (string.IsNullOrWhiteSpace(name))
        {
            throw new ArgumentException("Shopping list name is required.", nameof(name));
        }

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

        ShoppingListId = Guid.NewGuid();
        HouseholdId = householdId;
        Name = name.Trim();
        Status = ShoppingListStatus.Active;
        CreatedUtc = createdUtc;
        CreatedByUserId = createdByUserId;
    }

    public ShoppingListItem AddItem(string displayName, decimal? quantity, string? unit, string addedByUserId, DateTime addedUtc)
    {
        if (Status != ShoppingListStatus.Active)
        {
            throw new InvalidOperationException("Cannot add items to a list that is not active.");
        }

        var sortOrder = _items.Count == 0 ? 0 : _items.Max(i => i.SortOrder) + 1;
        var item = new ShoppingListItem(ShoppingListId, displayName, quantity, unit, sortOrder, addedByUserId, addedUtc);
        _items.Add(item);
        return item;
    }
}
