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 Target(serviceCatalogID string, targetName string, jobID string) (*rpc.Target, error) {
	foundService, err := Service(serviceCatalogID)
	if err != nil {
		return nil, err
	}

	httpClient := e2eutil.HTTPClientWithLDAP()
	targetsClient := rpc.NewTargetsProtobufClient(expected.TwirpEndpoint, httpClient)
	targetsResp, err := targetsClient.GetTargetsForService(context.Background(), &rpc.GetTargetsForServiceReq{
		ServiceId: foundService.GetId(),
	})
	if err != nil {
		return nil, err
	}

	var foundTarget *rpc.Target
	for _, target := range targetsResp.Targets {
		expectedTargetName := e2eutil.Suffix(targetName, jobID)
		if target.Name == expectedTargetName {
			foundTarget = target
		}
	}
	if foundTarget == nil {
		return nil, fmt.Errorf("no targets in DB with name '%q' for service target", targetName)
	}
	return foundTarget, nil
}
