package automation

import (
	"context"
	"strings"

	apperrors "github.com/nexuscrm/kernel/pkg/errors"
	"github.com/nexuscrm/kernel/pkg/formula"
	"github.com/nexuscrm/shared/pkg/constants"
	"github.com/nexuscrm/shared/pkg/models"
)

// selectedSystemRecordReader is the neutral Records-owned exact projection
// capability.  It is optional on the broad PersistenceProvider so existing
// non-production adapters do not silently acquire a new authority.
type selectedSystemRecordReader interface {
	ReadSelectedSystemRecord(ctx context.Context, objectName, recordID string, selectedFields []string) (models.Record, error)
}

func approvalLockRuleReadFields(schema *models.ObjectMetadata) ([]string, bool) {
	if schema == nil || schema.LockRule == nil || strings.TrimSpace(*schema.LockRule) == "" {
		return nil, true
	}
	fields, err := formula.CollectCurrentObjectFieldReferences(*schema.LockRule)
	if err != nil {
		return nil, false
	}
	for _, fieldName := range fields {
		field := models.FindField(schema, fieldName)
		if field == nil || field.IsVirtual || field.IsCompound {
			return nil, false
		}
	}
	return fields, true
}

func (s *ApprovalService) readApprovalSystemFields(ctx context.Context, objectName, recordID string, fields []string) (models.Record, error) {
	if s == nil || s.persistence == nil {
		return nil, apperrors.NewInternalError("approval persistence is not configured", nil)
	}
	canonical := make([]string, 0, len(fields)+1)
	seen := make(map[string]struct{}, len(fields)+1)
	for _, field := range append([]string{constants.FieldID}, fields...) {
		field = strings.TrimSpace(field)
		key := strings.ToLower(field)
		if field == "" {
			continue
		}
		if _, duplicate := seen[key]; duplicate {
			continue
		}
		seen[key] = struct{}{}
		canonical = append(canonical, field)
	}
	if reader, ok := s.persistence.(selectedSystemRecordReader); ok {
		return reader.ReadSelectedSystemRecord(ctx, objectName, recordID, canonical)
	}
	return nil, apperrors.NewInternalError("approval selected system-record reader is not configured", nil)
}
