/**
 * Lightweight, shared server-side validation + sanitisation for form
 * Route Handlers. Keeps each handler small while defending against bad input
 * before it reaches Strapi.
 */

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/

/** Trim a value to a string, collapsing internal whitespace/newlines. */
export function clean(value: unknown): string {
  if (value === null || value === undefined) return ""
  return String(value).replace(/\r/g, "").trim()
}

export function isEmail(value: string): boolean {
  return EMAIL_RE.test(value)
}

export function isNonEmpty(value: string): boolean {
  return value.length > 0
}

/** A string that meets the minimum and optionally maximum length. */
export function hasLength(
  value: string,
  min: number,
  max?: number
): boolean {
  if (value.length < min) return false
  if (max !== undefined && value.length > max) return false
  return true
}

/** Return true when the honeypot field is filled (i.e. a bot). */
export function isBot(honeypot: unknown): boolean {
  return clean(honeypot).length > 0
}

/** Match a value against an allow-list (e.g. event type options). */
export function isOneOf(value: string, allowed: readonly string[]): boolean {
  return allowed.includes(value)
}

/** Loose ISO date check (YYYY-MM-DD). */
export function isDate(value: string): boolean {
  return /^\d{4}-\d{2}-\d{2}$/.test(value)
}

/** Loose time check (HH:mm). */
export function isTime(value: string): boolean {
  return /^\d{2}:\d{2}$/.test(value)
}
