import type { ApplicationFormState } from './initiativeFormTypes';

type ParticipantRow = {
  id?: number;
  workUnit?: string;
};

/**
 * DOCX / template builders merge live `draft.application.authors` with last-saved
 * `contribution.participants`. Row IDs match {@link authorToContributionRow}; workplace
 * should follow the Đơn “Nơi công tác” field (dropdown) even when the contribution
 * tab JSON has not been re-saved.
 */
export function authorByIdMap(authors: ApplicationFormState['authors']): Map<
  number,
  ApplicationFormState['authors'][number]
> {
  return new Map(authors.map((x) => [x.id, x]));
}

export function resolveWorkUnitForContributionRow(
  authorById: Map<number, ApplicationFormState['authors'][number]>,
  p: ParticipantRow,
): string {
  const id = p.id;
  if (id != null) {
    const author = authorById.get(id);
    const fromAuthor = author?.workplace != null ? String(author.workplace).trim() : '';
    if (fromAuthor) return fromAuthor;
  }
  return p.workUnit != null ? String(p.workUnit).trim() : '';
}

type ContributionPositionSlice = { position?: string };

/**
 * TRANG BÌA « Đơn vị công tác » và Mẫu 02 « Đơn vị ».
 * `application.unitName` has no dedicated control on the Đơn form today, so we
 * fall back to tác giả đầu « Nơi công tác » (dropdown) then contribution « Chức vụ, đơn vị ».
 */
export function resolveDonViCongTacDisplay(
  a: ApplicationFormState,
  c: ContributionPositionSlice,
): string {
  const explicit = a.unitName != null ? String(a.unitName).trim() : '';
  if (explicit) return explicit;
  const w0 = a.authors[0]?.workplace != null ? String(a.authors[0].workplace).trim() : '';
  if (w0) return w0;
  const pos = c.position != null ? String(c.position).trim() : '';
  if (pos) return pos;
  return '';
}
