package packs

import (
	"context"

	connector "github.com/pingcap-inc/nexuscrm-contract/pkg/connector"
)

// newConnectorFieldMappingPackSweeperComponent is the synthetic pack-level
// component that guarantees stale _System_ObjectFieldMapping connector rows
// (Direction <> 'legacy') owned by this pack get soft-deleted on reapply when
// the new manifest no longer declares them.
//
// Without this, a pack version that drops a (SourceObject, TargetObject,
// ActionType, Direction) tuple or the entire connector_field_mapping component
// would leave the old rows live forever — runtime dispatch would keep reading
// them. Two-component packs would also silently break: applying component B
// would sweep component A's rows if the sweep were per-component instead of
// pack-level.
//
// Pattern mirrors newConnectorCapabilityPackSweeperComponent (connector_capability_sweeper.go).
//
// Synthetic component (NOT exposed via SourceBackedPack.Components or
// DeclaredComponents) — no payload hash contribution, no manifest business
// key, folded into InstallPlan/Verify only via lifecycleClosureComponents().
func newConnectorFieldMappingPackSweeperComponent(packName string, declared []connector.ConnectorFieldMappingInput) PackComponent {
	manifestComponent := ManifestComponent{
		Kind:          ComponentKindConnectorFieldMapping,
		BusinessKey:   "_pack_sweep",
		Manageability: ManageabilityLocked,
	}
	return &sourceBackedManagedComponent{
		packName:          packName,
		manifestComponent: manifestComponent,
		applyGroupKey:     string(ComponentKindConnectorFieldMapping),
		apply: func(ctx context.Context, deps ApplyDeps) error {
			return SweepConnectorFieldMappingsForOwner(ctx, deps.DB, packName, declared)
		},
		verify: func(ctx context.Context, deps VerifyDeps) error {
			return VerifyNoStaleConnectorFieldMappingsForOwner(ctx, deps.DB, packName, declared)
		},
	}
}
