package runtimeassembly

import (
	"context"
	"errors"

	"github.com/nexuscrm/automation"
	"github.com/nexuscrm/shared/pkg/models"
)

// ApprovalNotificationFlowRepository is the strict repository subset needed
// to build the descriptor catalog. Unlike the legacy MetadataService helpers,
// these reads retain repository failures so Runtime cannot publish a partial
// or fabricated empty result.
type ApprovalNotificationFlowRepository interface {
	GetAllFlowDefinitions(context.Context) ([]*models.FlowDefinition, error)
	GetFlowVersion(context.Context, string) (*models.FlowVersion, error)
}

type ApprovalNotificationFlowProtectedCatalog interface {
	ProtectedFlowNames(context.Context) ([]string, error)
}

// ApprovalNotificationFlowReadRuntime is the repository-backed neutral read
// graph for approval notification Flow descriptors. It owns no Flow executor,
// metadata mutation service, or Catalog serving projection.
type ApprovalNotificationFlowReadRuntime struct {
	repository ApprovalNotificationFlowRepository
	protected  ApprovalNotificationFlowProtectedCatalog
}

func NewApprovalNotificationFlowReadRuntime(
	repository ApprovalNotificationFlowRepository,
	protected ApprovalNotificationFlowProtectedCatalog,
) (*ApprovalNotificationFlowReadRuntime, error) {
	if repository == nil || protected == nil {
		return nil, errors.New("approval notification Flow read runtime requires repository and protected catalog")
	}
	return &ApprovalNotificationFlowReadRuntime{repository: repository, protected: protected}, nil
}

func (runtime *ApprovalNotificationFlowReadRuntime) ListApprovalNotificationFlows(
	ctx context.Context,
) ([]*models.FlowDefinition, error) {
	if runtime == nil {
		return nil, errors.New("approval notification Flow read runtime is unavailable")
	}
	return automation.ListApprovalNotificationFlowDefinitions(ctx, runtime)
}

func (runtime *ApprovalNotificationFlowReadRuntime) ApprovalNotificationFlowDefinitions(
	ctx context.Context,
) ([]*models.FlowDefinition, error) {
	return runtime.repository.GetAllFlowDefinitions(ctx)
}

func (runtime *ApprovalNotificationFlowReadRuntime) ApprovalNotificationFlowVersion(
	ctx context.Context,
	id string,
) (*models.FlowVersion, error) {
	return runtime.repository.GetFlowVersion(ctx, id)
}

func (runtime *ApprovalNotificationFlowReadRuntime) ProtectedFlowNames(
	ctx context.Context,
) ([]string, error) {
	return runtime.protected.ProtectedFlowNames(ctx)
}
