package subscriptions

import (
	"context"
	"strings"

	"github.com/tech/sendico/edge/callbacks/internal/model"
	"github.com/tech/sendico/edge/callbacks/internal/storage"
	"github.com/tech/sendico/pkg/merrors"
	"github.com/tech/sendico/pkg/mlogger"
	"github.com/tech/sendico/pkg/mutil/mzap"
	"go.mongodb.org/mongo-driver/v2/bson"
	"go.uber.org/zap"
)

type service struct {
	logger mlogger.Logger
	repo   storage.EndpointRepo
}

// New creates endpoint resolver service.
func New(deps Dependencies) (Resolver, error) {
	if deps.EndpointRepo == nil {
		return nil, merrors.InvalidArgument("subscriptions: endpoint repo is required", "endpointRepo")
	}
	logger := deps.Logger
	if logger == nil {
		logger = zap.NewNop()
	}

	return &service{
		logger: logger.Named("subscriptions"),
		repo:   deps.EndpointRepo,
	}, nil
}

func (s *service) Resolve(ctx context.Context, eventType string, organizationRef bson.ObjectID) ([]model.Endpoint, error) {
	if organizationRef == bson.NilObjectID {
		return nil, merrors.InvalidArgument("subscriptions: client id is required", "clientID")
	}
	if strings.TrimSpace(eventType) == "" {
		return nil, merrors.InvalidArgument("subscriptions: event type is required", "eventType")
	}

	endpoints, err := s.repo.FindActive(ctx, eventType, organizationRef)
	if err != nil {
		s.logger.Warn("Failed to resolve active endpoints",
			zap.String("event_type", eventType),
			mzap.ObjRef("organization_ref", organizationRef),
			zap.Error(err),
		)
		return nil, err
	}

	s.logger.Debug("Resolved active endpoints",
		zap.String("event_type", eventType),
		mzap.ObjRef("organization_ref", organizationRef),
		zap.Int("endpoints", len(endpoints)),
	)

	return endpoints, nil
}
