package handlers_test

import (
	"encoding/json"
	"time"

	"github.com/fiskerinc/cloud-services/services/attendant/services"

	"github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/fiskerinc/cloud-services/pkg/db/queries/mocks"
	"github.com/fiskerinc/cloud-services/pkg/redis"
	"github.com/fiskerinc/cloud-services/pkg/redis/tester"
	"github.com/go-pg/pg/v10/orm"
)

var mockRedis *redis.Connection
var mockDB *services.DB
var testDateTime time.Time = time.Date(2022, 1, 2, 3, 4, 5, 6, time.UTC)

func setupRedisMock() {
	redis.MockRedisConnection()
	mockRedis = &redis.Connection{}
}

func setupDBMock() {
	db := services.DB{}
	db.SetCarUpdates(&mocks.MockCarUpdates{
		SelectCarUpdateResponse: &common.CarUpdate{
			ID:               1,
			VIN:              "FISKER123",
			UpdateManifestID: 2,
			UpdateManifest: &common.UpdateManifest{
				ID:           2,
				Name:         "TEST_PACKAGE",
				Version:      "1.0.0",
				ReleaseNotes: "http://releasenotes.com",
				Country:      "US",
				PowerTrain:   "MD23",
				Restraint:    "None",
				Model:        "Ocean",
				Trim:         "Sport",
				Year:         2022,
				BodyType:     "truck",
			},
		},
	})
	db.SetECU(&mocks.MockEcuDtc{})
	db.SetCars(&mocks.MockCars{
		SelectResponse: &common.Car{},
	})
	carVersionLogMock := mocks.MockCarVersionsLog{MockLogVersionChange: func(log *common.CarVersionLogs) (orm.Result, error) {
		return nil, nil
	}}
	db.SetCarVersionsLog(&carVersionLogMock)
	mockDB = &db
}

type mockRedisCache struct {
	redis.Connection
}

func (c *mockRedisCache) GetSet(id string, data interface{}) error {
	driverIDs := []string{"valid-cognito-id-1", "valid-cognito-id-2"}

	dataBytes, err := json.Marshal(driverIDs)
	if err != nil {
		return err
	}

	err = json.Unmarshal(dataBytes, data)
	if err != nil {
		return err
	}

	return nil
}

func NewRedisMock() *tester.MockRedis {
	redis.MockRedisConnection()
	return &tester.MockRedis{}
}

type AttendentRouteTestCase struct {
	Name               string
	SelectCarUpdate    *common.CarUpdate
	SelectCarUpdates   []common.CarUpdate
	CarUpdateError     error
	SelectCarToDrivers []common.CarToDriver
	CarToDriversError  error
	MockLoadManifest   *common.UpdateManifest
	MockFileKeysSelect []common.FileKey
	MockFileKeysError  error
	MockEccKeysSelect  []common.ECCKeys
	tester.RedisTestCase
}

func (at *AttendentRouteTestCase) SetupDB(mockCars *mocks.MockCars, mockCarUpdates *mocks.MockCarUpdates, test *AttendentRouteTestCase) {
	if test == nil {
		return
	}

	if mockCars != nil {
		mockCars.SelectCarsForDrivers = test.SelectCarToDrivers
		mockCars.Error = test.CarToDriversError
	}

	if mockCarUpdates != nil {
		mockCarUpdates.SelectCarUpdateResponse = test.SelectCarUpdate
		mockCarUpdates.SelectCarUpdatesResponse = test.SelectCarUpdates
		mockCarUpdates.LoadManifest = test.MockLoadManifest
		mockCarUpdates.Error = test.CarUpdateError
	}
}
