package httpserver

import (
	"context"
	"fmt"

	"code.justin.tv/eventbus/controlplane/e2e/internal/e2eutil"
	"code.justin.tv/eventbus/controlplane/e2e/internal/expected"
	"code.justin.tv/eventbus/controlplane/rpc"
)

func Service(serviceCatalogID string) (*rpc.Service, error) {
	httpClient := e2eutil.HTTPClientWithLDAP()
	serviceClient := rpc.NewServicesProtobufClient(expected.TwirpEndpoint, httpClient)
	servicesResp, err := serviceClient.List(context.Background(), &rpc.ListServicesReq{})
	if err != nil {
		return nil, err
	}
	var foundService *rpc.Service
	for _, service := range servicesResp.Services {
		if service.ServiceCatalogUrl == expected.ServiceCatalogURL(serviceCatalogID) {
			foundService = service
			break
		}
	}
	if foundService == nil {
		return nil, fmt.Errorf("no service in seed DB with service catalog id '%q' for service target", serviceCatalogID)
	}
	return foundService, nil
}

func UpdateService(updated *rpc.Service) (*rpc.Service, error) {
	httpClient := e2eutil.HTTPClientWithLDAP()
	serviceClient := rpc.NewServicesProtobufClient(expected.TwirpEndpoint, httpClient)
	servicesResp, err := serviceClient.Update(context.Background(), &rpc.UpdateServiceReq{Service: updated})
	if err != nil {
		return nil, err
	}
	return servicesResp.Service, nil
}
