// Package serviceevent owns service-event subscription orchestration.
package serviceevent

import (
	"context"
	"strings"
)

// ServiceEventSubscriptionStore mutates service_event_* runtime truth.
//
// During the App facade migration the implementation may also update legacy
// App compatibility projections, but callers must treat service_event_* records
// as the source of truth.
type ServiceEventSubscriptionStore interface {
	BlockServiceEventSubscriptions(ctx context.Context, workspaceID, provider, connectionRef string) (int, error)
	UnblockServiceEventSubscriptions(ctx context.Context, workspaceID, provider, connectionRef string) (int, error)
}

// ServiceEventSubscriptionService coordinates service-event subscription state
// changes for provider connection availability. Provider-specific resolution
// remains behind the runtime store adapter until that persistence logic moves
// fully into serviceactor.
type ServiceEventSubscriptionService struct {
	store ServiceEventSubscriptionStore
}

// NewServiceEventSubscriptionCoordinator constructs the service-event
// subscription coordinator used by App/provider API facades.
func NewServiceEventSubscriptionCoordinator(store ServiceEventSubscriptionStore) *ServiceEventSubscriptionService {
	return &ServiceEventSubscriptionService{store: store}
}

// BlockServiceEventSubscriptions blocks runtime subscriptions affected by a
// provider connection becoming unavailable. The method name remains compatible
// with App/provider API facade ports.
func (service *ServiceEventSubscriptionService) BlockServiceEventSubscriptions(ctx context.Context, workspaceID, provider, connectionRef string) (int, error) {
	if service == nil || service.store == nil {
		return 0, nil
	}
	return service.store.BlockServiceEventSubscriptions(ctx, strings.TrimSpace(workspaceID), strings.TrimSpace(provider), strings.TrimSpace(connectionRef))
}

// UnblockServiceEventSubscriptions restores runtime subscriptions affected by a
// provider connection becoming available. The method name remains compatible
// with App/provider API facade ports.
func (service *ServiceEventSubscriptionService) UnblockServiceEventSubscriptions(ctx context.Context, workspaceID, provider, connectionRef string) (int, error) {
	if service == nil || service.store == nil {
		return 0, nil
	}
	return service.store.UnblockServiceEventSubscriptions(ctx, strings.TrimSpace(workspaceID), strings.TrimSpace(provider), strings.TrimSpace(connectionRef))
}
