package cache_test

import (
	"fmt"
	"testing"

	"github.com/fiskerinc/cloud-services/pkg/cache"
	"github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/fiskerinc/cloud-services/pkg/db/queries"
	"github.com/fiskerinc/cloud-services/pkg/redis"
	"github.com/fiskerinc/cloud-services/pkg/testhelper"
	"github.com/google/uuid"
)

func TestRetrieveSubscriptionTypes(t *testing.T) {
	t.Skip()
	query := queries.SubscriptionTypes{}
	client := redis.NewClient()
	subtype, err := setupTestSubscritionType(&query)
	if err != nil {
		t.Error(err)
		return
	}
	defer cleanupTestSubscriptionType(client, &query, subtype)

	list, err := cache.RetrieveSubscriptionTypesList(client, &query)
	if err != nil {
		t.Error(err)
	}
	if len(list) == 0 {
		t.Errorf(testhelper.TestErrorTemplate, "From DB", "1 or more", len(list))
	}

	list, err = cache.RetrieveSubscriptionTypesList(client, &query)
	if err != nil {
		t.Error(err)
	}
	if len(list) == 0 {
		t.Errorf(testhelper.TestErrorTemplate, "From Redis", "1 or more", len(list))
	}

	item, err := cache.RetrieveSubscriptionType(client, &query, subtype.ID)
	if err != nil {
		t.Error(err)
	}

	if item.Name != subtype.Name {
		t.Errorf(testhelper.TestErrorTemplate, "RetrieveSubscriptionType From DB", subtype.Name, item.Name)
	}

	item, err = cache.RetrieveSubscriptionType(client, &query, subtype.ID)
	if err != nil {
		t.Error(err)
	}

	if item.Name != subtype.Name {
		t.Errorf(testhelper.TestErrorTemplate, "RetrieveSubscriptionType From Redis", subtype.Name, item.Name)
	}

	item, err = cache.RetrieveSubscriptionType(client, &query, uuid.New())
	if err == nil {
		t.Errorf(testhelper.TestErrorTemplate, "Invalid subscription type id", "found out", err)
	}
	if item != nil {
		t.Errorf(testhelper.TestErrorTemplate, "Invalid subscription type item", nil, item)
	}
}

func setupTestSubscritionType(query *queries.SubscriptionTypes) (*common.SubscriptionType, error) {
	subtype := common.SubscriptionType{
		Name:          fmt.Sprintf("Test type %s", uuid.New().String()),
		Destination:   "ICC",
		Description:   "test",
		Currency:      "USD",
		Price:         10000, // $100 USD
		DurationValue: 1,
		DurationUnit:  "Hours",
	}
	_, err := query.Insert(&subtype)

	return &subtype, err
}

func cleanupTestSubscriptionType(client redis.Client, query *queries.SubscriptionTypes, subtype *common.SubscriptionType) {
	client.Delete(redis.SubscriptionTypeListKey(subtype.ID))
	client.Delete(redis.SubscriptionTypeListKey(uuid.Nil))
	query.Delete(subtype)
}
