package handlers_test

import (
	"fmt"
	"net/http"
	"testing"

	"otaupdate/handlers"
	"otaupdate/services"

	m "github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/fiskerinc/cloud-services/pkg/db/queries/mocks"
	"github.com/fiskerinc/cloud-services/pkg/mongo"
	th "github.com/fiskerinc/cloud-services/pkg/testhelper"
	"github.com/fiskerinc/cloud-services/pkg/utils/elptr"
)

func TestAddVehicle(t *testing.T) {
	client, err := services.GetMongoClient()
	if err != nil {
		t.Error(err)
		return
	}
	mock := mocks.MockCars{}
	services.GetDB().SetCars(&mock)
	client.SetVehicles(mongo.NewVehiclesCollection(&mongo.MockCollection{}))

	tests := []mocks.DBHttpTest{
		{
			Name:             "No data",
			Request:          th.MakeTestRequest(http.MethodPost, "http://example.com/vehicle", nil),
			ExpectedStatus:   http.StatusBadRequest,
			ExpectedResponse: `{"message":"VIN required","error":"Bad Request"}`,
		},
		{
			Name:             "No VIN",
			Request:          th.MakeTestRequest(http.MethodPost, "http://example.com/vehicle", m.AddCarRequest{}),
			ExpectedStatus:   http.StatusBadRequest,
			ExpectedResponse: `{"message":"VIN required","error":"Bad Request"}`,
		},
		{
			Name: "Bad data",
			Request: th.MakeTestRequest(http.MethodPost, "http://example.com/vehicle", m.AddCarRequest{
				VIN: "XXXXXXXXXXXXXXXXXXXXX",
			}),
			ExpectedStatus:   http.StatusBadRequest,
			ExpectedResponse: `{"message":"VIN 'XXXXXXXXXXXXXXXXXXXXX' invalid","error":"Bad Request"}`,
		},
		{
			Name: "Good data",
			Request: th.MakeTestRequest(http.MethodPost, "http://example.com/vehicle", m.AddCarRequest{
				VIN: "1G1FP87S3GN100062",
				CANBus: &m.CANBus{
					Enabled:    true,
					DataLogger: false,
					DTCEnabled: elptr.ElPtr(false),
				},
				IDPSEnabled: true,
			}),
			ExpectedStatus:   http.StatusOK,
			ExpectedResponse: `{"vin":"1G1FP87S3GN100062","canbus":{"enabled":true,"data_logger_enabled":false,"dtc_enabled":false},"idps_enabled":true}`,
		},
		{
			Name: "Good data, no CANBus",
			Request: th.MakeTestRequest(http.MethodPost, "http://example.com/vehicle", m.AddCarRequest{
				VIN: "1G1FP87S3GN100062",
			}),
			ExpectedStatus:   http.StatusOK,
			ExpectedResponse: `{"vin":"1G1FP87S3GN100062","canbus":{"enabled":true,"data_logger_enabled":false,"dtc_enabled":true}}`,
		},
		{
			Name: "Error",
			Request: th.MakeTestRequest(http.MethodPost, "http://example.com/vehicle", m.AddCarRequest{
				VIN: "1G1FP87S3GN100062",
			}),
			ExpectedStatus:   http.StatusServiceUnavailable,
			ExpectedResponse: `{"message":"something went wrong","error":"Service Unavailable"}`,
			DBTestCase: mocks.DBTestCase{
				MockError: fmt.Errorf("something went wrong"),
			},
		},
	}

	mocks.RunDBTests(t, tests, handlers.HandleVehicleAdd, &mock)
}
