package serverruntime

import (
	"fmt"

	"github.com/nexuscrm/automation"
	"github.com/nexuscrm/backend/internal/application/services"
	database "github.com/nexuscrm/db"
	"github.com/nexuscrm/events"
)

// BuildConnectorInboundRemoteIdentityRecoveryMaintenance composes the same L0
// recovery engine, installed-source resolver, durable store, record locking,
// and product lifecycle validator used by the protected runtime action. The
// app-blind distribution has no lifecycle validator and therefore fails closed;
// the CRM distribution supplies its pure validator through ProductHooks.
func BuildConnectorInboundRemoteIdentityRecoveryMaintenance(
	conn *database.TiDBConnection,
	hooks ProductHooks,
) (*automation.ConnectorInboundRemoteIdentityRecoveryService, error) {
	if conn == nil || conn.DB() == nil {
		return nil, fmt.Errorf("connector remote identity recovery maintenance database is not wired")
	}
	validator := hooks.Capabilities.ConnectorInboundRemoteIdentityRecoveryValidator
	if validator == nil {
		return nil, fmt.Errorf("connector remote identity recovery maintenance product lifecycle validator is not wired")
	}

	infraDeps := buildInfrastructureDeps(conn)
	infraDeps.EventBus = &events.NoOpEventBus{}
	infraDeps.OnEventDropped = func(string) {}
	infraDeps.OnQueueUtilizationChange = func(float64) {}
	infraDeps.ApprovalDefinitionDecoder = hooks.Capabilities.ApprovalDefinitionDecoder
	infraDeps.ApprovalQueryOnlyOwnerPacks = append([]string(nil), hooks.Capabilities.ApprovalQueryOnlyOwnerPacks...)
	svcMgr, err := services.NewServiceManager(infraDeps)
	if err != nil {
		return nil, fmt.Errorf("compose connector remote identity recovery maintenance services: %w", err)
	}
	if svcMgr.FlowExecutor == nil || svcMgr.Persistence == nil || svcMgr.TxManager == nil {
		return nil, fmt.Errorf("connector remote identity recovery maintenance service graph is incomplete")
	}

	generations := newConnectorPushGenerationResolver(conn.DB())
	installed := newConnectorPushContractResolver(conn.DB(), hooks.ComponentKindRegistrationSet())
	installed.generations = generations
	installed.txExtractor = svcMgr.TxManager
	svcMgr.FlowExecutor.SetConnectorPushProfileResolver(connectorPushProfileResolver{db: conn.DB(), generations: generations})
	svcMgr.FlowExecutor.SetConnectorPushContractResolver(installed)
	svcMgr.FlowExecutor.SetConnectorInboundRemoteIdentityInstalledContractResolver(installed)

	store := automation.NewSQLConnectorPushDurableStoreWithTxExtractor(conn.DB(), svcMgr.TxManager)
	return automation.NewConnectorInboundRemoteIdentityRecoveryService(
		svcMgr.Persistence,
		store,
		svcMgr.FlowExecutor,
		automation.NewConnectorInboundRemoteIdentityRecoverySourceValidator(svcMgr.Persistence, validator),
	), nil
}
