package handlers_test

import (
	"testing"

	"github.com/fiskerinc/cloud-services/services/depot/handlers"
	"github.com/fiskerinc/cloud-services/services/depot/services"

	"github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/fiskerinc/cloud-services/pkg/db/queries/mocks"
	"github.com/fiskerinc/cloud-services/pkg/grpc/sms"
	"github.com/fiskerinc/cloud-services/pkg/mongo"
	"github.com/fiskerinc/cloud-services/pkg/redis"
	"github.com/fiskerinc/cloud-services/pkg/redis/tester"
	"github.com/fiskerinc/cloud-services/pkg/testhelper"
	"github.com/fiskerinc/cloud-services/pkg/userconsent"
)

func TestTrexInit(t *testing.T) {
	rMock := tester.MockRedis{}
	rMock.Reset()

	mockUserConsent := userconsent.UserConsentServiceMock{}
	userconsent.SetUserConsentService(&mockUserConsent)

	mockCert := CertServiceMock{}
	services.SetCertService(&mockCert)

	services.SetRedisClientPool(tester.NewMockClientPool(&rMock))
	id := "FISKER123"

	setupDBMock()
	services.SetMongoClient(mongo.NewMockClient())

	mockCertificates := mocks.MockCertificates{}
	mockCertificates.MockCertificate = &common.Certificate{
		PublicKey:    "test",
		SerialNumber: "",
		Type:         common.CertTBOX,
	}
	services.GetDB().SetCertificates(&mockCertificates)

	mocksms := sms.NewSMSMockSuccess()
	services.SetSmsClient(&mocksms)

	err := handlers.TRexInit(
		id,
		map[string]string{"version": "1.2.3", "iccid": "123456789123456789123456789", "ip": "172.20.0.17:49850"})
	if err != nil {
		t.Errorf(testhelper.TestErrorTemplate, "TestTRexInit", nil, err)
	}

	rez := rMock.SetValues[redis.CarStateHashKey(id)]
	if rez.Value.(string) != `{"ip":"172.20.0.17","trex_version":"1.2.3"}` {
		t.Errorf(testhelper.TestErrorTemplate, "TestTRexInit_wrongVersion", `{"ip":"172.20.0.17","trex_version":"1.2.3"}`, rez.Value)
	}

	rez = rMock.SetValues[redis.CarConfigKey(id)]
	if rez.Value.(string) != `{"canbus":{"enabled":false,"data_logger_enabled":false,"dtc_enabled":false},"log_level":"trace","log":{"matches":[{"channel":"cmd","level":"trace"}]}}` {
		t.Errorf(testhelper.TestErrorTemplate, "TestTRexInit_wrongVersion", `{"canbus":{"enabled":false,"data_logger_enabled":false,"dtc_enabled":false},"log_level":"trace"}`, rez.Value)
	}
}

type CertServiceMock struct{}

func (csm *CertServiceMock) CheckCertificateNeedsRenewal(vin string, certType string) (bool, error) {
	return certType == common.CertTBOX, nil
}

func (csm *CertServiceMock) RenewCertificate(vin string, certType string) (*common.Certificate, error) {
	cert := common.Certificate{
		PublicKey:    "test",
		SerialNumber: "",
		Type:         common.CertTBOX,
	}

	return &cert, nil
}
