namespace EntKube.Identity.Domain;

/// <summary>
/// A Tenant represents an organization or team using the EntKube platform.
/// Each tenant has isolated access to clusters and provisioned services.
/// The Identity service owns tenant lifecycle (creation, suspension, deletion)
/// and user membership within tenants.
/// </summary>
public class Tenant
{
    public Guid Id { get; private set; }
    public string Name { get; private set; } = string.Empty;
    public string Slug { get; private set; } = string.Empty;
    public TenantStatus Status { get; private set; }
    public DateTimeOffset CreatedAt { get; private set; }

    private readonly List<TenantMember> members = new();
    public IReadOnlyList<TenantMember> Members => members.AsReadOnly();

    private Tenant() { }

    /// <summary>
    /// Creates a new tenant in the platform. The creating user automatically
    /// becomes the tenant's first admin member.
    /// </summary>
    public static Tenant Create(string name, string slug, Guid creatingUserId)
    {
        if (string.IsNullOrWhiteSpace(name))
        {
            throw new ArgumentException("Tenant name is required.", nameof(name));
        }

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

        Tenant tenant = new()
        {
            Id = Guid.NewGuid(),
            Name = name,
            Slug = slug.ToLowerInvariant(),
            Status = TenantStatus.Active,
            CreatedAt = DateTimeOffset.UtcNow
        };

        // The creator is automatically the admin of their new tenant.

        tenant.members.Add(new TenantMember(creatingUserId, TenantRole.Admin));

        return tenant;
    }

    /// <summary>
    /// Adds a user to this tenant with the specified role.
    /// </summary>
    public void AddMember(Guid userId, TenantRole role)
    {
        if (members.Any(m => m.UserId == userId))
        {
            return;
        }

        members.Add(new TenantMember(userId, role));
    }

    public void Suspend()
    {
        Status = TenantStatus.Suspended;
    }

    public void Activate()
    {
        Status = TenantStatus.Active;
    }
}

public record TenantMember(Guid UserId, TenantRole Role);

public enum TenantStatus
{
    Active,
    Suspended
}

public enum TenantRole
{
    Admin,
    Member,
    Viewer
}
