package files

import (
	"strings"

	"github.com/nexuscrm/backend/internal/features/mru"
	"github.com/nexuscrm/shared/pkg/constants"
)

var canonicalObjectAPINames = map[string]string{
	"account":     "Account",
	"campaign":    "Campaign",
	"case":        "Case",
	"comment":     constants.TableComment,
	"contact":     "Contact",
	"contract":    "Contract",
	"lead":        "Lead",
	"opportunity": "Opportunity",
	"order":       "Order",
	"quote":       "Quote",
	"user":        "User",
}

func canonicalizeObjectAPIName(objectAPIName string) string {
	objectAPIName = strings.TrimSpace(objectAPIName)
	if canonical, ok := canonicalObjectAPINames[strings.ToLower(objectAPIName)]; ok {
		return canonical
	}
	return objectAPIName
}

// NormalizeParentObjectAPIName returns a stable API name for persisted file rows.
// It prefers the object inferred from the record ID when available, and otherwise
// canonicalizes common standard object names case-insensitively.
func NormalizeParentObjectAPIName(parentID, parentObjectAPIName string) string {
	parentID = strings.TrimSpace(parentID)
	parentObjectAPIName = strings.TrimSpace(parentObjectAPIName)

	if inferred, ok := mru.ResolveTypeFromID(parentID); ok {
		if parentObjectAPIName == "" || strings.EqualFold(parentObjectAPIName, inferred) {
			return canonicalizeObjectAPIName(inferred)
		}
	}

	return canonicalizeObjectAPIName(parentObjectAPIName)
}
