package routing

import (
	"context"
	"testing"
	"time"

	"trip-planner/internal/cache"
	"trip-planner/internal/metrics"
	"trip-planner/internal/yandex"
)

// mockCacheStoreForSearch is a mock implementation of Cache for testing search cache
type mockCacheStoreForSearch struct {
	data map[string][]byte
}

func (m *mockCacheStoreForSearch) Get(ctx context.Context, key *cache.CacheKey) ([]byte, error) {
	keyStr := key.Kind + ":" + key.Code
	if data, ok := m.data[keyStr]; ok {
		return data, nil
	}
	return nil, nil
}

func (m *mockCacheStoreForSearch) Set(ctx context.Context, key *cache.CacheKey, value []byte, ttl time.Duration) error {
	keyStr := key.Kind + ":" + key.Code
	m.data[keyStr] = value
	return nil
}

func (m *mockCacheStoreForSearch) Exists(ctx context.Context, key *cache.CacheKey) (bool, error) {
	keyStr := key.Kind + ":" + key.Code
	_, ok := m.data[keyStr]
	return ok, nil
}

func (m *mockCacheStoreForSearch) Delete(ctx context.Context, key *cache.CacheKey) error {
	keyStr := key.Kind + ":" + key.Code
	delete(m.data, keyStr)
	return nil
}

func (m *mockCacheStoreForSearch) Increment(ctx context.Context, key *cache.CacheKey) (int64, error) {
	return 0, nil
}

func (m *mockCacheStoreForSearch) Decrement(ctx context.Context, key *cache.CacheKey) (int64, error) {
	return 0, nil
}

func TestNewSearchCacheService(t *testing.T) {
	mockStore := &mockCacheStoreForSearch{data: make(map[string][]byte)}
	metrics := metrics.New()
	yclient := yandex.NewClient("test-key")

	svc := NewSearchCacheService(mockStore, yclient, metrics)
	if svc == nil {
		t.Error("expected SearchCacheService to be created")
	}
	if svc.cache == nil {
		t.Error("expected cache to be initialized")
	}
	if svc.yclient == nil {
		t.Error("expected yclient to be initialized")
	}
	if svc.metrics == nil {
		t.Error("expected metrics to be initialized")
	}
}

func TestConvertResponseToBytes(t *testing.T) {
	// Test with nil response
	_, err := convertResponseToBytes(nil)
	if err == nil {
		t.Error("expected error for nil response")
	}

	// Test with valid response
	resp := &yandex.Response{
		Segments: []yandex.Segment{},
	}
	data, err := convertResponseToBytes(resp)
	if err != nil {
		t.Errorf("expected no error, got %v", err)
	}
	if data == nil {
		t.Error("expected non-nil data")
	}
}
