package httpserver

import (
	"context"

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

func AllowIAMRolePublish(jobID, eventType, environment, iamRole string, opts ...Option) (*rpc.AllowIAMRolePublishResp, error) {
	c := defaultConfig()
	for _, opt := range opts {
		opt(c)
	}

	httpClient := e2eutil.HTTPClientWithLDAPUserAndGroups(c.ldapUser, c.ldapGroups)
	infraClient := rpc.NewInfrastructureProtobufClient(expected.TwirpEndpoint, httpClient)
	return infraClient.AllowIAMRolePublish(context.Background(), &rpc.AllowIAMRolePublishReq{
		EventType:   e2eutil.Suffix(eventType, jobID),
		Environment: environment,
		IamRole:     iamRole,
	})
}

func DeleteIAMRolePublication(jobID, eventType, environment, iamRole string, opts ...Option) (*rpc.DeleteIAMRolePublicationResp, error) {
	c := defaultConfig()
	for _, opt := range opts {
		opt(c)
	}

	httpClient := e2eutil.HTTPClientWithLDAPUserAndGroups(c.ldapUser, c.ldapGroups)
	infraClient := rpc.NewInfrastructureProtobufClient(expected.TwirpEndpoint, httpClient)
	return infraClient.DeleteIAMRolePublication(context.Background(), &rpc.DeleteIAMRolePublicationReq{
		EventType:   e2eutil.Suffix(eventType, jobID),
		Environment: environment,
		IamRoleArn:  iamRole,
	})
}

func CreateAuthorizedFieldSubscriberGrant(jobID, eventType, environment, messageName, fieldName, iamRole string, opts ...Option) (*rpc.CreateAuthorizedFieldSubscriberGrantResp, error) {
	c := defaultConfig()
	for _, opt := range opts {
		opt(c)
	}

	httpClient := e2eutil.HTTPClientWithLDAPUserAndGroups(c.ldapUser, c.ldapGroups)
	infraClient := rpc.NewInfrastructureProtobufClient(expected.TwirpEndpoint, httpClient)
	return infraClient.CreateAuthorizedFieldSubscriberGrant(context.Background(), &rpc.CreateAuthorizedFieldSubscriberGrantReq{
		EventType:   e2eutil.Suffix(eventType, jobID),
		Environment: environment,
		AuthorizedField: &rpc.AuthorizedField{
			MessageName: messageName,
			FieldName:   fieldName,
		},
		IamRole: iamRole,
	})
}

func DeleteAuthorizedFieldSubscriberGrant(jobID, eventType, environment, messageName, fieldName, iamRole string, opts ...Option) (*rpc.DeleteAuthorizedFieldSubscriberGrantResp, error) {
	c := defaultConfig()
	for _, opt := range opts {
		opt(c)
	}

	httpClient := e2eutil.HTTPClientWithLDAPUserAndGroups(c.ldapUser, c.ldapGroups)
	infraClient := rpc.NewInfrastructureProtobufClient(expected.TwirpEndpoint, httpClient)
	return infraClient.DeleteAuthorizedFieldSubscriberGrant(context.Background(), &rpc.DeleteAuthorizedFieldSubscriberGrantReq{
		Grant: &rpc.AuthorizedFieldSubscriberGrant{
			EventType:   e2eutil.Suffix(eventType, jobID),
			Environment: environment,
			IamRole:     iamRole,
			AuthorizedField: &rpc.AuthorizedField{
				MessageName: messageName,
				FieldName:   fieldName,
			},
		},
	})
}
