export interface CorrespondentReference {
  id?: string | null;
  name?: string | null;
  key?: string;
}

import type { Document } from '../types/documents';

export interface ResolvedCorrespondent {
  id?: string | null;
  name: string;
  key: string;
}

export const resolveCorrespondents = (doc?: Document | null): ResolvedCorrespondent[] => {
  if (!doc || !Array.isArray(doc.correspondents)) {
    return [];
  }

  const seen = new Set<string>();
  const results: ResolvedCorrespondent[] = [];

  doc.correspondents.forEach((entry = {}, index) => {
    const { id, name } = entry;
    const trimmedName = name?.trim?.();
    if (!trimmedName) {
      return;
    }

    if (id != null && seen.has(id)) {
      return;
    }

    if (id != null) {
      seen.add(id);
    }

    results.push({
      id,
      name: trimmedName,
      key: id ?? `${trimmedName}-${index}`,
    });
  });

  return results;
};

export default resolveCorrespondents;
