package teamworkflow

import (
	"strings"

	storeteamworkflow "github.com/tidbcloud/AgentTeam/internal/store/teamworkflow"
)

// LifecycleEventSink receives a refresh hint after an authoritative Team
// Workflow lifecycle mutation commits. The event deliberately carries only
// stable resource identity and revision: consumers must re-read the Team
// Workflow collection/detail instead of treating this callback as state.
//
// SourceScopeID is the owning Team Channel and is part of the contract so a
// transport can route the hint only to current viewers of that Team scope.
type LifecycleEventSink interface {
	EmitTeamWorkflowsUpdated(
		workspaceID string,
		sourceScopeID string,
		teamID string,
		teamWorkflowID string,
		revision int64,
	)
}

// ServiceOptions configures optional post-commit Team Workflow projections.
type ServiceOptions struct {
	LifecycleEvents LifecycleEventSink
}

func (service *Service) emitLifecycleUpdated(relation storeteamworkflow.TeamWorkflow) {
	if service == nil || service.lifecycleEvents == nil {
		return
	}
	workspaceID := strings.TrimSpace(relation.WorkspaceID)
	sourceScopeID := strings.TrimSpace(relation.SourceScopeID)
	teamID := strings.TrimSpace(relation.TeamID)
	teamWorkflowID := strings.TrimSpace(relation.ID)
	if workspaceID == "" || sourceScopeID == "" || teamID == "" || teamWorkflowID == "" || relation.Revision <= 0 {
		return
	}
	service.lifecycleEvents.EmitTeamWorkflowsUpdated(
		workspaceID,
		sourceScopeID,
		teamID,
		teamWorkflowID,
		relation.Revision,
	)
}
