import Fuse from "fuse.js"
import {
  MAIL_SETTINGS_SEARCH_INDEX,
  type MailSettingsSearchEntry,
} from "@/lib/mail-settings/settings-search-index"

const fuse = new Fuse(MAIL_SETTINGS_SEARCH_INDEX, {
  keys: [
    { name: "label", weight: 0.45 },
    { name: "sectionLabel", weight: 0.2 },
    { name: "keywords", weight: 0.25 },
    { name: "description", weight: 0.1 },
  ],
  threshold: 0.38,
  ignoreLocation: true,
})

export function searchMailSettings(query: string, limit = 8): MailSettingsSearchEntry[] {
  const trimmed = query.trim()
  if (!trimmed) return []
  return fuse.search(trimmed, { limit }).map((result) => result.item)
}
