using EntKube.Identity.Domain;
using FluentAssertions;

namespace EntKube.Identity.Tests.Domain;

public class TenantTests
{
    [Fact]
    public void Create_WithValidInputs_CreatesTenantWithAdminMember()
    {
        // Arrange & Act — An admin creates a new tenant organization.

        Guid userId = Guid.NewGuid();
        Tenant tenant = Tenant.Create("Acme Corp", "acme-corp", userId);

        // Assert — The tenant should be active and the creator should be admin.

        tenant.Id.Should().NotBe(Guid.Empty);
        tenant.Name.Should().Be("Acme Corp");
        tenant.Slug.Should().Be("acme-corp");
        tenant.Status.Should().Be(TenantStatus.Active);
        tenant.Members.Should().HaveCount(1);
        tenant.Members[0].UserId.Should().Be(userId);
        tenant.Members[0].Role.Should().Be(TenantRole.Admin);
    }

    [Fact]
    public void Create_WithEmptyName_ThrowsArgumentException()
    {
        // Arrange & Act

        Action act = () => Tenant.Create("", "slug", Guid.NewGuid());

        // Assert

        act.Should().Throw<ArgumentException>()
            .WithParameterName("name");
    }

    [Fact]
    public void Create_WithEmptySlug_ThrowsArgumentException()
    {
        // Arrange & Act

        Action act = () => Tenant.Create("Acme", "", Guid.NewGuid());

        // Assert

        act.Should().Throw<ArgumentException>()
            .WithParameterName("slug");
    }

    [Fact]
    public void AddMember_NewUser_AddsMemberToTenant()
    {
        // Arrange

        Tenant tenant = Tenant.Create("Acme", "acme", Guid.NewGuid());
        Guid newUserId = Guid.NewGuid();

        // Act

        tenant.AddMember(newUserId, TenantRole.Member);

        // Assert

        tenant.Members.Should().HaveCount(2);
        tenant.Members.Should().Contain(m => m.UserId == newUserId && m.Role == TenantRole.Member);
    }

    [Fact]
    public void AddMember_ExistingUser_DoesNotDuplicate()
    {
        // Arrange — Create a tenant (creator is already a member).

        Guid userId = Guid.NewGuid();
        Tenant tenant = Tenant.Create("Acme", "acme", userId);

        // Act — Try adding the same user again.

        tenant.AddMember(userId, TenantRole.Viewer);

        // Assert — Still only one member.

        tenant.Members.Should().HaveCount(1);
    }

    [Fact]
    public void Suspend_SetsStatusToSuspended()
    {
        // Arrange

        Tenant tenant = Tenant.Create("Acme", "acme", Guid.NewGuid());

        // Act

        tenant.Suspend();

        // Assert

        tenant.Status.Should().Be(TenantStatus.Suspended);
    }
}
