package automation

import (
	"context"
	"database/sql"

	"github.com/nexuscrm/backend/internal/bootstrap"
)

// bootstrapFieldMappingApplier is the production FieldMappingApplier. It
// resolves rows from _System_ObjectFieldMapping via the bootstrap package
// (the canonical registry reader) and copies fields from source to target
// using the same rules the legacy convertLead handler consumed. Keeping
// the lookup behind the FieldMappingApplier interface keeps the bootstrap
// dependency out of FlowExecutor proper.
type bootstrapFieldMappingApplier struct {
	db *sql.DB
}

// NewBootstrapFieldMappingApplier returns a FieldMappingApplier that reads
// the registry directly from rawDB. Intended for service-manager wiring.
func NewBootstrapFieldMappingApplier(rawDB *sql.DB) FieldMappingApplier {
	return &bootstrapFieldMappingApplier{db: rawDB}
}

func (a *bootstrapFieldMappingApplier) ApplyMappings(ctx context.Context, sourceObject, targetObject, actionType string, source, target map[string]interface{}) error {
	mappings, err := bootstrap.GetFieldMappings(a.db, sourceObject, targetObject, actionType)
	if err != nil {
		return err
	}
	bootstrap.ApplyFieldMappings(mappings, source, target)
	return nil
}
