package mapping

import (
	"fmt"
	"strings"

	"qctextbuilder/internal/domain"
)

type Service interface {
	AssembleAIData(fields []domain.TemplateField, values map[string]string) (map[string]map[string]any, error)
}

type RawKeyService struct{}

func New() *RawKeyService {
	return &RawKeyService{}
}

func (s *RawKeyService) AssembleAIData(fields []domain.TemplateField, values map[string]string) (map[string]map[string]any, error) {
	allowed := make(map[string]domain.TemplateField, len(fields))
	for _, f := range fields {
		if !f.IsEnabled || f.FieldKind != "text" {
			continue
		}
		allowed[f.Path] = f
	}

	out := make(map[string]map[string]any)
	for path, value := range values {
		if strings.TrimSpace(value) == "" {
			continue
		}
		f, ok := allowed[path]
		if !ok {
			return nil, fmt.Errorf("unknown or disabled field path: %s", path)
		}
		if out[f.Section] == nil {
			out[f.Section] = make(map[string]any)
		}
		out[f.Section][f.KeyName] = value
	}
	return out, nil
}
