using ColaFlow.Shared.Kernel.Common;
using ColaFlow.Modules.Identity.Domain.Aggregates.Tenants;

namespace ColaFlow.Modules.Identity.Domain.Aggregates.Users;

/// <summary>
/// Represents a user's role within a specific tenant
/// </summary>
public sealed class UserTenantRole : Entity
{
    public UserId UserId { get; private set; } = null!;
    public TenantId TenantId { get; private set; } = null!;
    public TenantRole Role { get; private set; }

    public DateTime AssignedAt { get; private set; }
    public Guid? AssignedByUserId { get; private set; }

    // Navigation properties (optional, for EF Core)
    public User User { get; private set; } = null!;
    public Tenant Tenant { get; private set; } = null!;

    // Private constructor for EF Core
    private UserTenantRole() : base()
    {
    }

    /// <summary>
    /// Factory method to create a user-tenant-role assignment
    /// </summary>
    public static UserTenantRole Create(
        UserId userId,
        TenantId tenantId,
        TenantRole role,
        Guid? assignedByUserId = null)
    {
        return new UserTenantRole
        {
            Id = Guid.NewGuid(),
            UserId = userId,
            TenantId = tenantId,
            Role = role,
            AssignedAt = DateTime.UtcNow,
            AssignedByUserId = assignedByUserId
        };
    }

    /// <summary>
    /// Update the user's role (e.g., promote Member to Admin)
    /// </summary>
    public void UpdateRole(TenantRole newRole, Guid updatedByUserId)
    {
        if (Role == newRole)
            return;

        Role = newRole;
        AssignedByUserId = updatedByUserId;
        // Note: AssignedAt is NOT updated to preserve original assignment timestamp
    }

    /// <summary>
    /// Check if user has permission (extensible for future fine-grained permissions)
    /// </summary>
    public bool HasPermission(string permission)
    {
        // Future implementation: Check permission against role-permission mapping
        // For now, this is a placeholder for fine-grained permission checks
        return Role switch
        {
            TenantRole.TenantOwner => true, // Owner has all permissions
            TenantRole.AIAgent when permission.StartsWith("read") => true,
            TenantRole.AIAgent when permission.StartsWith("write_preview") => true,
            _ => false // Implement specific permission checks as needed
        };
    }
}
