namespace ColaFlow.Modules.Mcp.Domain.ValueObjects;

/// <summary>
/// Value object representing API Key permissions
/// </summary>
public sealed class ApiKeyPermissions
{
    /// <summary>
    /// Allow read access to MCP resources
    /// </summary>
    public bool Read { get; set; } = true;

    /// <summary>
    /// Allow write access via MCP tools
    /// </summary>
    public bool Write { get; set; } = false;

    /// <summary>
    /// List of allowed resource URIs (empty = all allowed)
    /// Example: ["project://123", "epic://456"]
    /// </summary>
    public List<string> AllowedResources { get; set; } = new();

    /// <summary>
    /// List of allowed tool names (empty = all allowed)
    /// Example: ["create_task", "update_story"]
    /// </summary>
    public List<string> AllowedTools { get; set; } = new();

    /// <summary>
    /// Private constructor for EF Core
    /// </summary>
    private ApiKeyPermissions()
    {
    }

    /// <summary>
    /// Create a read-only permission set
    /// </summary>
    public static ApiKeyPermissions ReadOnly()
    {
        return new ApiKeyPermissions
        {
            Read = true,
            Write = false,
            AllowedResources = new(),
            AllowedTools = new()
        };
    }

    /// <summary>
    /// Create a read-write permission set
    /// </summary>
    public static ApiKeyPermissions ReadWrite()
    {
        return new ApiKeyPermissions
        {
            Read = true,
            Write = true,
            AllowedResources = new(),
            AllowedTools = new()
        };
    }

    /// <summary>
    /// Create a custom permission set
    /// </summary>
    public static ApiKeyPermissions Custom(
        bool read,
        bool write,
        List<string>? allowedResources = null,
        List<string>? allowedTools = null)
    {
        return new ApiKeyPermissions
        {
            Read = read,
            Write = write,
            AllowedResources = allowedResources ?? new(),
            AllowedTools = allowedTools ?? new()
        };
    }

    /// <summary>
    /// Check if the permission allows the specified resource
    /// </summary>
    public bool CanAccessResource(string resourceUri)
    {
        // If no restrictions, allow all
        if (AllowedResources.Count == 0)
            return Read;

        return AllowedResources.Contains(resourceUri);
    }

    /// <summary>
    /// Check if the permission allows the specified tool
    /// </summary>
    public bool CanUseTool(string toolName)
    {
        // If no restrictions, allow all (if write enabled)
        if (AllowedTools.Count == 0)
            return Write;

        return AllowedTools.Contains(toolName);
    }
}
