// Copyright 2026 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package tidbmanager

import (
	"context"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"github.com/stretchr/testify/require"
)

func TestClientFreeWithActiveDurationIsCompatibleWithOldManager(t *testing.T) {
	var received *http.Request
	var returnedToFreeCache bool
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		received = req
		// Old managers with CONNECTION_IDLE_DELAY enabled require an exact reason match.
		parts := strings.SplitN(req.URL.Query().Get("normal_restart_log"), ":", 2)
		returnedToFreeCache = len(parts) == 2 && parts[1] == "connection idle for too long"
		w.WriteHeader(http.StatusOK)
	}))
	defer server.Close()

	client := NewClient(
		strings.TrimPrefix(server.URL, "http://"),
		nil,
		"tidb-0",
		"10.0.0.1",
		"tidb-pool",
	)

	err := client.Free(
		context.Background(),
		"keyspace:connection idle for too long",
		"42",
	)

	require.NoError(t, err)
	require.NotNil(t, received)
	require.True(t, returnedToFreeCache)
	require.Equal(t, http.MethodPut, received.Method)
	require.Equal(t, "tidb-0", received.URL.Query().Get("pod_name"))
	require.Equal(t, "10.0.0.1", received.URL.Query().Get("pod_ip"))
	require.Equal(t, "tidb-pool", received.URL.Query().Get("ns"))
	require.Equal(t, "keyspace:connection idle for too long",
		received.URL.Query().Get("normal_restart_log"))
	require.Equal(t, "42", received.URL.Query().Get(activeSecondsQueryName))
}

func TestClientFreeWithoutActiveDuration(t *testing.T) {
	var received *http.Request
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		received = req
		w.WriteHeader(http.StatusOK)
	}))
	defer server.Close()

	client := NewClient(
		strings.TrimPrefix(server.URL, "http://"),
		nil,
		"tidb-0",
		"10.0.0.1",
		"tidb-pool",
	)

	err := client.Free(context.Background(), "keyspace:connection idle for too long", "")

	require.NoError(t, err)
	require.NotNil(t, received)
	require.NotContains(t, received.URL.Query(), activeSecondsQueryName)
}
