package observability

import (
	"context"

	"go.uber.org/zap"

	"code.justin.tv/eventbus/controlplane/internal/db"
)

func (o *ObservabilityDB) EventTypeAndStreamsCreate(ctx context.Context, eventType *db.EventType, environments []string) ([]*db.EventStream, error) {
	var err error
	var eventStreams []*db.EventStream
	o.observe(ctx, "EventTypeAndStreamsCreate", func() ([]zap.Field, error) {
		eventStreams, err = o.db.EventTypeAndStreamsCreate(ctx, eventType, environments)
		eventStreamsLoggable := &eventStreamsList{eventStreams}
		// Little hack to get the eventTypeID for the originally submitted eventType
		var eventTypeID int
		if len(eventStreams) > 0 {
			eventTypeID = eventStreams[0].EventTypeID
		}
		cpy := *eventType
		cpy.ID = eventTypeID
		return []zap.Field{
			zap.Array("eventStreams", eventStreamsLoggable),
			zap.Object("eventType", cpy),
		}, err
	})
	return eventStreams, err
}
func (o *ObservabilityDB) EventStreamPublisherAccounts(ctx context.Context, eventStreamID int) ([]*db.Account, error) {
	var err error
	var accts []*db.Account
	o.observe(ctx, "EventStreamPublisherAccounts",
		func() ([]zap.Field, error) {
			accts, err = o.db.EventStreamPublisherAccounts(ctx, eventStreamID)
			return []zap.Field{
				zap.Int("eventStreamID", eventStreamID),
			}, err
		})
	return accts, err
}
func (o *ObservabilityDB) EventStreamPublisherIAMRoles(ctx context.Context, eventStreamID int) ([]*db.IAMRole, error) {
	var err error
	var iamRoles []*db.IAMRole
	o.observe(ctx, "EventStreamPublisherIAMRoles",
		func() ([]zap.Field, error) {
			iamRoles, err = o.db.EventStreamPublisherIAMRoles(ctx, eventStreamID)
			return []zap.Field{
				zap.Int("eventStreamID", eventStreamID),
			}, err
		})
	return iamRoles, err
}
func (o *ObservabilityDB) PublisherServicesByEventStreamID(ctx context.Context, eventStreamID int) ([]*db.Service, error) {
	var err error
	var services []*db.Service
	o.observe(ctx, "PublisherServicesByEventStreamID",
		func() ([]zap.Field, error) {
			services, err = o.db.PublisherServicesByEventStreamID(ctx, eventStreamID)
			return []zap.Field{
				zap.Int("eventStreamID", eventStreamID),
			}, err
		})
	return services, err
}

func (o *ObservabilityDB) ServicesSubscribedToEventType(ctx context.Context, eventType string) ([]*db.Service, error) {
	var err error
	var services []*db.Service
	o.observe(ctx, "ServicesSubscribedToEventType",
		func() ([]zap.Field, error) {
			services, err = o.db.ServicesSubscribedToEventType(ctx, eventType)
			return []zap.Field{
				zap.String("eventType", eventType),
			}, err
		})
	return services, err
}
