export type PeoplePickerItemKind = "account" | "contact" | "external" | "function" | (string & {});

export type PeoplePickerItem = {
  selection_key: string;
  kind: PeoplePickerItemKind;
  reference_id?: string | null;
  display_name: string;
  email?: string | null;
  source_module?: string | null;
  source_label?: string | null;
  source_ref?: string | null;
  source_revision?: string | null;
  description?: string | null;
  provenance?: Record<string, unknown>;
  metadata?: Record<string, unknown>;
};

export type PeoplePickerSearchCandidate = PeoplePickerItem & {
  disabled?: boolean;
  disabled_reason?: string | null;
};

export type PeoplePickerSearchGroup = {
  key: string;
  label: string;
  candidates: readonly PeoplePickerSearchCandidate[];
};

export type PeoplePickerSearchOptions = {
  limit: number;
  signal: AbortSignal;
};

export type PeoplePickerSearch = (
  query: string,
  options: PeoplePickerSearchOptions
) => Promise<readonly PeoplePickerSearchGroup[]>;

export function peoplePickerDedupeKey(item: Pick<PeoplePickerItem, "selection_key" | "email">): string {
  const email = item.email?.trim().toLowerCase();
  return email ? `email:${email}` : `selection:${item.selection_key.trim().toLowerCase()}`;
}

export function dedupePeoplePickerItems(items: readonly PeoplePickerItem[]): PeoplePickerItem[] {
  const seen = new Set<string>();
  const result: PeoplePickerItem[] = [];
  for (const item of items) {
    const key = peoplePickerDedupeKey(item);
    if (!item.selection_key.trim() || seen.has(key)) continue;
    seen.add(key);
    result.push(item);
  }
  return result;
}

export function externalPeoplePickerItem(displayName: string, email?: string | null): PeoplePickerItem {
  const normalizedName = displayName.trim();
  const normalizedEmail = email?.trim().toLowerCase() || null;
  const identityPart = normalizedEmail || normalizedName.toLowerCase();
  return {
    selection_key: `external:${identityPart}`,
    kind: "external",
    reference_id: null,
    display_name: normalizedName,
    email: normalizedEmail,
    source_module: null,
    source_label: "i18n:govoplan-core.external_person.35115d8e",
    source_ref: null,
    source_revision: null,
    provenance: {},
    metadata: { manual: true }
  };
}

export function selectionFromPeoplePickerCandidate(candidate: PeoplePickerSearchCandidate): PeoplePickerItem {
  const { disabled: _disabled, disabled_reason: _disabledReason, ...selection } = candidate;
  return selection;
}
