package automation

import (
	"context"
	"fmt"
	"strings"

	"github.com/nexuscrm/shared/pkg/constants"
	"github.com/nexuscrm/shared/pkg/contract"
)

// ConnectorRemoteIdentityOwnerDeleteLifecycleCapability is declared by an L1
// object only when deleting that object must quarantine its remote identities.
const ConnectorRemoteIdentityOwnerDeleteLifecycleCapability = "connector.remote-identity.owner-delete"

// ConnectorRemoteIdentityOwnerDeleteLifecycleStore is the transaction-scoped
// durable-link transition needed after a record owner is deleted.
type ConnectorRemoteIdentityOwnerDeleteLifecycleStore interface {
	QuarantineFinalizedRemoteIdentitiesForDeletedOwnerInAmbientTx(ctx context.Context, objectName, recordID string) error
	ClearConnectorRemoteIdentityOwnerDeletedFenceForRestoredOwnerInAmbientTx(ctx context.Context, objectName, recordID string) error
}

// NewConnectorRemoteIdentityOwnerDeleteLifecycleHook constructs the generic
// L0 hook. Product metadata decides which record types opt in; the hook itself
// only changes local durable state and therefore never blocks on remote I/O.
func NewConnectorRemoteIdentityOwnerDeleteLifecycleHook(store ConnectorRemoteIdentityOwnerDeleteLifecycleStore) (contract.RecordLifecycleHook, error) {
	if store == nil {
		return nil, fmt.Errorf("connector remote identity owner-delete lifecycle store is required")
	}
	return func(ctx context.Context, event contract.RecordLifecycleEvent) error {
		objectName := strings.TrimSpace(event.ObjectName)
		recordID := strings.TrimSpace(event.RecordID)
		if objectName == "" || recordID == "" {
			return fmt.Errorf("connector remote identity owner-delete lifecycle event requires object name and record id")
		}
		return store.QuarantineFinalizedRemoteIdentitiesForDeletedOwnerInAmbientTx(ctx, objectName, recordID)
	}, nil
}

// NewConnectorRemoteIdentityOwnerRestoreLifecycleHook clears only the owner
// admission fence after the records engine restores a deleted record. It does
// not recover or rebind quarantined remote links.
func NewConnectorRemoteIdentityOwnerRestoreLifecycleHook(store ConnectorRemoteIdentityOwnerDeleteLifecycleStore) (contract.RecordLifecycleHook, error) {
	if store == nil {
		return nil, fmt.Errorf("connector remote identity owner-restore lifecycle store is required")
	}
	return func(ctx context.Context, event contract.RecordLifecycleEvent) error {
		if event.OldRecord[constants.FieldIsDeleted] != true || event.Record[constants.FieldIsDeleted] != false {
			return nil
		}
		objectName := strings.TrimSpace(event.ObjectName)
		recordID := strings.TrimSpace(event.RecordID)
		if objectName == "" || recordID == "" {
			return fmt.Errorf("connector remote identity owner-restore lifecycle event requires object name and record id")
		}
		return store.ClearConnectorRemoteIdentityOwnerDeletedFenceForRestoredOwnerInAmbientTx(ctx, objectName, recordID)
	}, nil
}
