namespace NATS.Server.JetStream.Api.Handlers;

public static class ClusterControlApiHandlers
{
    public static JetStreamApiResponse HandleMetaLeaderStepdown(JetStream.Cluster.JetStreamMetaGroup meta)
    {
        meta.StepDown();
        return JetStreamApiResponse.SuccessResponse();
    }

    public static JetStreamApiResponse HandleStreamLeaderStepdown(string subject, StreamManager streams)
    {
        if (!subject.StartsWith(JetStreamApiSubjects.StreamLeaderStepdown, StringComparison.Ordinal))
            return JetStreamApiResponse.NotFound(subject);

        var stream = subject[JetStreamApiSubjects.StreamLeaderStepdown.Length..].Trim();
        if (stream.Length == 0)
            return JetStreamApiResponse.NotFound(subject);

        streams.StepDownStreamLeaderAsync(stream, default).GetAwaiter().GetResult();
        return JetStreamApiResponse.SuccessResponse();
    }

    public static JetStreamApiResponse HandleStreamPeerRemove(string subject)
    {
        if (!subject.StartsWith(JetStreamApiSubjects.StreamPeerRemove, StringComparison.Ordinal))
            return JetStreamApiResponse.NotFound(subject);

        var stream = subject[JetStreamApiSubjects.StreamPeerRemove.Length..].Trim();
        return stream.Length == 0 ? JetStreamApiResponse.NotFound(subject) : JetStreamApiResponse.SuccessResponse();
    }

    public static JetStreamApiResponse HandleConsumerLeaderStepdown(string subject)
    {
        if (!subject.StartsWith(JetStreamApiSubjects.ConsumerLeaderStepdown, StringComparison.Ordinal))
            return JetStreamApiResponse.NotFound(subject);

        var remainder = subject[JetStreamApiSubjects.ConsumerLeaderStepdown.Length..].Trim();
        var tokens = remainder.Split('.', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
        return tokens.Length == 2 ? JetStreamApiResponse.SuccessResponse() : JetStreamApiResponse.NotFound(subject);
    }
}
