package search

import (
	"strings"

	"github.com/ultisuite/ulti-backend/internal/api/apivalidate"
)

const (
	minSearchQueryLen = 1
	maxSearchQueryLen = 500
)

var allowedSearchTypes = map[string]struct{}{
	"mail":     {},
	"contacts": {},
	"files":    {},
	"events":   {},
}

func validateSearchQuery(q string) *apivalidate.ValidationError {
	q = strings.TrimSpace(q)
	if q == "" {
		return apivalidate.NewValidationError(apivalidate.FieldDetail{
			Field: "q", Message: "required",
		})
	}
	if len(q) < minSearchQueryLen {
		return apivalidate.NewValidationError(apivalidate.FieldDetail{
			Field: "q", Message: "too short",
		})
	}
	if len(q) > maxSearchQueryLen {
		return apivalidate.NewValidationError(apivalidate.FieldDetail{
			Field: "q", Message: "too long",
		})
	}
	return nil
}

func validateSearchTypes(typesRaw string) *apivalidate.ValidationError {
	if strings.TrimSpace(typesRaw) == "" {
		return nil
	}
	for _, part := range strings.Split(typesRaw, ",") {
		t := strings.TrimSpace(part)
		if t == "" {
			continue
		}
		if _, ok := allowedSearchTypes[t]; !ok {
			return apivalidate.NewValidationError(apivalidate.FieldDetail{
				Field: "types", Message: "invalid value: " + t,
			})
		}
	}
	return nil
}
