using System.Text.Json.Serialization;

namespace ColaFlow.Modules.Mcp.Contracts.JsonRpc;

/// <summary>
/// JSON-RPC 2.0 request object
/// </summary>
public class JsonRpcRequest
{
    /// <summary>
    /// A String specifying the version of the JSON-RPC protocol. MUST be exactly "2.0"
    /// </summary>
    [JsonPropertyName("jsonrpc")]
    public string JsonRpc { get; set; } = "2.0";

    /// <summary>
    /// A String containing the name of the method to be invoked
    /// </summary>
    [JsonPropertyName("method")]
    public string Method { get; set; } = string.Empty;

    /// <summary>
    /// A Structured value that holds the parameter values to be used during the invocation of the method (optional)
    /// </summary>
    [JsonPropertyName("params")]
    [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
    public object? Params { get; set; }

    /// <summary>
    /// An identifier established by the Client. If not included, it's a notification (optional)
    /// </summary>
    [JsonPropertyName("id")]
    [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
    public object? Id { get; set; }

    /// <summary>
    /// Indicates if this is a notification (no response expected)
    /// </summary>
    [JsonIgnore]
    public bool IsNotification => Id == null;

    /// <summary>
    /// Validates the JSON-RPC request structure
    /// </summary>
    public bool IsValid(out string? errorMessage)
    {
        if (JsonRpc != "2.0")
        {
            errorMessage = "jsonrpc must be exactly '2.0'";
            return false;
        }

        if (string.IsNullOrWhiteSpace(Method))
        {
            errorMessage = "method is required";
            return false;
        }

        errorMessage = null;
        return true;
    }
}
