//go:build crm

package crm

import (
	"fmt"

	"github.com/nexuscrm/automation"
	dialectsfcrm "github.com/nexuscrm/dialect-sf-crm"
	"github.com/nexuscrm/shared/pkg/contract"
)

const recoverConnectorRemoteIdentityHandlerRef = "platform:connector/recover-remote-identity"

func recoverConnectorRemoteIdentityFlowActionCallHandlerImplementation() automation.FlowActionCallHandlerImplementation {
	return automation.FlowActionCallHandlerImplementation{
		HandlerRef: recoverConnectorRemoteIdentityHandlerRef,
		Build: func(descriptor automation.FlowActionCallRegistrationDescriptor) (automation.FlowActionCallRegistration, error) {
			return automation.FlowActionCallRegistration{
				ActionType:      descriptor.ActionType,
				HandlerRef:      descriptor.HandlerRef,
				AtomicPolicy:    automation.FlowActionCallAtomicPolicyReject,
				PreviewPolicy:   automation.FlowActionCallPreviewPolicyReject,
				RequiresContext: automation.FlowActionCallContextNone,
				Handler: automation.NewConnectorInboundRemoteIdentityRecoveryFlowActionHandler(
					descriptor.ActionType,
					crmConnectorInboundRemoteIdentityRecoveryValidator{},
				),
			}, nil
		},
	}
}

type crmConnectorInboundRemoteIdentityRecoveryValidator struct{}

func (crmConnectorInboundRemoteIdentityRecoveryValidator) ValidateConnectorInboundRemoteIdentityRecoveryLockedRecord(
	input automation.ConnectorInboundRemoteIdentityRecoveryLockedRecordInput,
) (automation.ConnectorPushCompatibilityMirrorStatus, error) {
	state, err := dialectsfcrm.ValidateConnectorInboundRemoteIdentityRecoverySource(
		dialectsfcrm.ConnectorInboundRemoteIdentityRecoverySourceInput{
			ObjectName:    input.ObjectName,
			RecordID:      input.RecordID,
			Record:        contract.Record(input.Record),
			RemoteIDField: input.RemoteIDField,
			RemoteID:      input.RemoteID,
		},
	)
	if err != nil {
		return "", err
	}
	switch state {
	case dialectsfcrm.ConnectorInboundRemoteIdentityRecoveryMirrorSynced:
		return automation.ConnectorPushCompatibilityMirrorSynced, nil
	case dialectsfcrm.ConnectorInboundRemoteIdentityRecoveryMirrorDrifted:
		return automation.ConnectorPushCompatibilityMirrorDrifted, nil
	default:
		return "", fmt.Errorf("CRM connector recovery validator returned unsupported mirror state %q", state)
	}
}
