package handlers_test

import (
	"net/http"
	"otaupdate/handlers"
	"otaupdate/services"
	"testing"

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

func TestUpdateManifestUpdate(t *testing.T) {
	services.GetDB().SetUpdateManifests(&mocks.MockUpdateManifests{})

	tests := []th.BasicHttpTest{
		{
			Name:             "No id",
			Request:          th.MakeTestRequest(http.MethodGet, "http://example.com/manifest", nil),
			ExpectedStatus:   http.StatusBadRequest,
			ExpectedResponse: `{"message":"id required","error":"Bad Request"}`,
		},
		{
			Name:             "Zero id",
			Request:          th.MakeTestRequest(http.MethodGet, "http://example.com/manifest?id=0", nil),
			ExpectedStatus:   http.StatusBadRequest,
			ExpectedResponse: `{"message":"id required","error":"Bad Request"}`,
		},
		{
			Name: "Validation error, empty manifest",
			Request: th.MakeTestRequest(
				http.MethodGet,
				"http://example.com/manifest?id=1",
				common.UpdateManifestUpdateRequest{}),
			ExpectedStatus:   http.StatusBadRequest,
			ExpectedResponse: `{"message":"Name required. Type required","error":"Bad Request"}`,
		},
		{
			Name: "Success",
			Request: th.MakeTestRequest(
				http.MethodGet,
				"http://example.com/manifest?id=1",
				common.UpdateManifestUpdateRequest{
					Name:           "new_name",
					Type:           "standard",
					Country:        "US",
					PowerTrain:     "None",
					Restraint:      "MD12",
					Model:          "Ocean",
					Trim:           "Sport",
					Year:           2022,
					BodyType:       "trailer",
					UpdateDuration: 30,
					MaxAttempts:    5,
					ReleaseNotes:   "https://fiskerinc.com",
				}),
			ExpectedStatus:   http.StatusOK,
			ExpectedResponse: `{"id":1,"name":"new_name","release_notes":"https://fiskerinc.com","rollback":false,"type":"standard","country":"US","powertrain":"None","restraint":"MD12","model":"Ocean","trim":"Sport","year":2022,"body_type":"trailer","update_duration":30,"max_attempts":5}`,
		},
		{
			Name: "Active",
			Request: th.MakeTestRequest(
				http.MethodGet,
				"http://example.com/manifest?id=1",
				common.UpdateManifestUpdateRequest{Name: "new_name", Type: "standard", Active: elptr.ElPtr(false)}),
			ExpectedStatus:   http.StatusOK,
			ExpectedResponse: `{"id":1,"name":"new_name","rollback":false,"type":"standard","active":false}`,
		},
	}

	th.RunBasicHttpTests(t, tests, handlers.HandleUpdateManifestUpdate)
}
