using System.Text.Json;

namespace JsonRpcEndpointSample.Rpc.Abstractions;

public abstract class RpcRequestHandler<TRequest, TResponse> : IRpcRequestHandler
    where TRequest : class
{
    public async Task<object?> HandleAsync(JsonElement parameters)
    {
        TRequest? request = parameters.Deserialize<TRequest>(JsonRpcSerializerOptions.Default);

        if (request == null)
        {
            throw new InvalidOperationException("Invalid RPC parameters.");
        }

        TResponse response = await HandleRequestAsync(request);
        return response;
    }

    protected abstract Task<TResponse> HandleRequestAsync(TRequest request);
}
