import type { FullContact } from "./types"

export type ContactBulkEditField =
  | "company"
  | "department"
  | "jobTitle"
  | "website"
  | "notes"

export const CONTACT_BULK_EDIT_FIELDS: {
  id: ContactBulkEditField
  label: string
}[] = [
  { id: "company", label: "Entreprise" },
  { id: "department", label: "Service" },
  { id: "jobTitle", label: "Poste" },
  { id: "website", label: "Site web" },
  { id: "notes", label: "Notes" },
]

export function getContactBulkFieldValue(
  contact: FullContact,
  field: ContactBulkEditField,
): string {
  const raw = contact[field]
  return typeof raw === "string" ? raw.trim() : ""
}

export function collectBulkFieldSuggestions(
  contacts: FullContact[],
  field: ContactBulkEditField,
): string[] {
  const seen = new Set<string>()
  const out: string[] = []
  for (const contact of contacts) {
    const value = getContactBulkFieldValue(contact, field)
    if (!value) continue
    const key = value.toLowerCase()
    if (seen.has(key)) continue
    seen.add(key)
    out.push(value)
  }
  return out.sort((a, b) => a.localeCompare(b, "fr"))
}

export function applyBulkFieldValue(
  contact: FullContact,
  field: ContactBulkEditField,
  value: string,
): FullContact {
  const trimmed = value.trim()
  return {
    ...contact,
    [field]: trimmed || undefined,
    updatedAt: Date.now(),
  }
}
