package packs

import (
	"fmt"
	"strings"
)

type declaredCustomFieldExtension struct {
	ObjectAPIName string
	Field         FieldSpec
}

func resolveDeclaredCustomFieldExtension(specs []ObjectSpec, objectAPIName, fieldAPIName string) (declaredCustomFieldExtension, error) {
	objectAPIName = strings.TrimSpace(objectAPIName)
	fieldAPIName = strings.TrimSpace(fieldAPIName)
	if objectAPIName == "" || fieldAPIName == "" {
		return declaredCustomFieldExtension{}, fmt.Errorf("custom field extension requires non-empty objectApiName and fieldApiName")
	}
	if !isCustomFieldAPIName(fieldAPIName) {
		return declaredCustomFieldExtension{}, fmt.Errorf("%s.%s must be a custom field declaration", objectAPIName, fieldAPIName)
	}

	for _, spec := range specs {
		if strings.TrimSpace(spec.APIName) != objectAPIName {
			continue
		}
		for _, field := range spec.Fields {
			if strings.TrimSpace(field.APIName) != fieldAPIName {
				continue
			}
			if !isCustomFieldAPIName(field.APIName) {
				return declaredCustomFieldExtension{}, fmt.Errorf("%s.%s must be a custom field declaration", objectAPIName, fieldAPIName)
			}
			return declaredCustomFieldExtension{
				ObjectAPIName: objectAPIName,
				Field:         field,
			}, nil
		}
		return declaredCustomFieldExtension{}, fmt.Errorf("%s.%s is not declared by object_spec payload", objectAPIName, fieldAPIName)
	}
	return declaredCustomFieldExtension{}, fmt.Errorf("%s.%s is not declared by object_spec payload", objectAPIName, fieldAPIName)
}
