/******************************************************************************
 * Copyright (c)  2023 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 regionalservice

import (
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"github.com/tidbcloud/observability/pkg/common/structs"
)

func TestRuleCache(t *testing.T) {
	cacheConfig := structs.OverlayAlertRuleCacheConfig{
		ExpireTime:          3 * time.Second,
		MaxItems:            2,
		MaxDeletionPerCycle: 2,
		SleepTime:           1 * time.Second,
	}
	data := make([]structs.AlertRuleGroup, 0)
	InitAlertRuleCache(cacheConfig)
	t.Run("set suc", func(t *testing.T) {
		ruleQueryCache.set("key1", data)
		ruleQueryCache.set("key2", data)
		ruleQueryCache.set("key3", data)
		_, ok1 := ruleQueryCache.get("key1")
		_, ok2 := ruleQueryCache.get("key2")
		_, ok3 := ruleQueryCache.get("key3")
		assert.True(t, ok1)
		assert.True(t, ok2)
		assert.True(t, ok3)
	})

	t.Run("set failed for reach the max items", func(t *testing.T) {
		ruleQueryCache.set("key4", data)
		_, ok := ruleQueryCache.get("key4")
		assert.False(t, ok)
	})

	t.Run("delete suc", func(t *testing.T) {
		ruleQueryCache.delete("key3")
		_, ok := ruleQueryCache.get("key3")
		assert.False(t, ok)
	})

	time.Sleep(1 * time.Second)
	t.Run("get suc", func(t *testing.T) {
		_, ok1 := ruleQueryCache.get("key1")
		_, ok2 := ruleQueryCache.get("key2")
		assert.True(t, ok1)
		assert.True(t, ok2)
	})

	time.Sleep(3 * time.Second)

	t.Run("check expire", func(t *testing.T) {
		_, ok1 := ruleQueryCache.get("key1")
		_, ok2 := ruleQueryCache.get("key2")
		assert.False(t, ok1)
		assert.False(t, ok2)
	})

}
