package packs

import (
	"context"
	"fmt"

	"github.com/nexuscrm/kernel/pkg/formula"
)

func newSourceBackedFormulaFunctionBundleComponent(packName string, component ManifestComponent, payload []byte) (PackComponent, formula.FunctionBundle, error) {
	bundle, err := formula.ParseFunctionBundlePayload(payload)
	if err != nil {
		return nil, formula.FunctionBundle{}, fmt.Errorf("parse %s: %w", componentPayloadLabel(component), err)
	}
	return &sourceBackedManagedComponent{
		packName:          packName,
		manifestComponent: component,
		payload:           payload,
		expectedProjection: func() (any, error) {
			return bundle, nil
		},
		liveProjection: func(_ context.Context, _ VerifyDeps) (any, error) {
			return bundle, nil
		},
		apply: func(_ context.Context, _ ApplyDeps) error {
			return nil
		},
		verify: func(_ context.Context, _ VerifyDeps) error {
			return formula.ValidateFunctionBundles([]formula.FunctionBundle{bundle})
		},
	}, bundle, nil
}
