package handlers_test

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

	"github.com/fiskerinc/cloud-services/pkg/common"

	mo "github.com/fiskerinc/cloud-services/pkg/db/queries/mocks"
	th "github.com/fiskerinc/cloud-services/pkg/testhelper"
	"github.com/google/uuid"
)

func TestSubscriptionPackageGetObject(t *testing.T) {
	mock := mo.MockSubscriptionPackages{}
	services.GetDB().SetSubPackages(&mock)
	expectedFilter := &common.SubscriptionPackage{
		ID: uuid.MustParse("0557bd1d-76d3-41e5-a44e-13c479e55ab0"),
	}
	expectedResp := `{"id":"0557bd1d-76d3-41e5-a44e-13c479e55ab0","name":"Test Package","features":[{"id":"6666bd1d-76d3-41e5-a44e-13c479e55ab6","name":"Test Feature","description":"Feature Description"}]}`
	data := common.SubscriptionPackage{
		ID:   uuid.MustParse("0557bd1d-76d3-41e5-a44e-13c479e55ab0"),
		Name: "Test Package",
		Features: []common.SubscriptionFeature{
			{
				ID:          uuid.MustParse("6666bd1d-76d3-41e5-a44e-13c479e55ab6"),
				Name:        "Test Feature",
				Description: "Feature Description",
			},
		},
	}

	tests := []mo.DBHttpTest{
		{
			Name:             "No parameters",
			Request:          th.MakeTestRequest(http.MethodGet, "http://example.com/subscriptionpackage", nil),
			ExpectedStatus:   http.StatusBadRequest,
			ExpectedResponse: `{"message":"primary key required","error":"Bad Request"}`,
		},
		{
			Name:             "Id parameter",
			Request:          th.MakeTestRequest(http.MethodGet, "http://example.com/subscriptionpackage?id=0557bd1d-76d3-41e5-a44e-13c479e55ab0", nil),
			ExpectedStatus:   http.StatusOK,
			ExpectedResponse: expectedResp,
			DBTestCase: mo.DBTestCase{
				ExpectedFilter:   expectedFilter,
				MockLoadResponse: data,
			},
		},
		{
			Name:             "Name parameter",
			Request:          th.MakeTestRequest(http.MethodGet, "http://example.com/subscriptionpackage?name=Test%20Package", nil),
			ExpectedStatus:   http.StatusOK,
			ExpectedResponse: expectedResp,
			DBTestCase: mo.DBTestCase{
				ExpectedFilter: &common.SubscriptionPackage{
					Name: "Test Package",
				},
				MockLoadResponse: data,
			},
		},
		{
			Name:             "Error",
			Request:          th.MakeTestRequest(http.MethodGet, "http://example.com/subscriptionpackage?id=0557bd1d-76d3-41e5-a44e-13c479e55ab0", nil),
			ExpectedStatus:   http.StatusServiceUnavailable,
			ExpectedResponse: `{"message":"something went wrong","error":"Service Unavailable"}`,
			DBTestCase: mo.DBTestCase{
				ExpectedFilter: expectedFilter,
				MockError:      fmt.Errorf("something went wrong"),
			},
		},
	}

	mo.RunDBTests(t, tests, handlers.HandleSubscriptionPackageGet, &mock)
}
