using CartWise.Domain.Enums;

namespace CartWise.Domain.Entities;

public class Household
{
    private readonly List<HouseholdMember> _members = [];

    public Guid HouseholdId { get; private set; }

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

    public DateTime CreatedUtc { get; private set; }

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

    public IReadOnlyCollection<HouseholdMember> Members => _members.AsReadOnly();

    private Household()
    {
    }

    public Household(string name, string createdByUserId, DateTime createdUtc)
    {
        if (string.IsNullOrWhiteSpace(name))
        {
            throw new ArgumentException("Household name is required.", nameof(name));
        }

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

        HouseholdId = Guid.NewGuid();
        Name = name.Trim();
        CreatedByUserId = createdByUserId;
        CreatedUtc = createdUtc;

        _members.Add(new HouseholdMember(HouseholdId, createdByUserId, HouseholdRole.Owner, createdUtc));
    }

    public HouseholdMember AddMember(string userId, HouseholdRole role, DateTime joinedUtc)
    {
        if (_members.Any(m => m.UserId == userId))
        {
            throw new InvalidOperationException("User is already a member of this household.");
        }

        var member = new HouseholdMember(HouseholdId, userId, role, joinedUtc);
        _members.Add(member);
        return member;
    }

    public bool IsMember(string userId) => _members.Any(m => m.UserId == userId);
}
