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

/** Columns shown on “Bản Xác Nhận” tỷ lệ đóng góp — maps to {@link Author} fields used on Đơn §1. */
export type ContributionParticipantColumn = 'fullName' | 'workUnit' | 'contributionPercent';

export function contributionColumnToAuthorField(
  col: ContributionParticipantColumn,
): keyof Pick<Author, 'name' | 'workplace' | 'contributionPercent'> {
  switch (col) {
    case 'fullName':
      return 'name';
    case 'workUnit':
      return 'workplace';
    case 'contributionPercent':
      return 'contributionPercent';
  }
}

export function authorToContributionRow(
  author: Author,
  isEditing: boolean,
): {
  id: number;
  fullName: string;
  workUnit: string;
  contributionPercent: number;
  isEditing: boolean;
} {
  return {
    id: author.id,
    fullName: author.name,
    workUnit: author.workplace,
    contributionPercent: Number(author.contributionPercent) || 0,
    isEditing,
  };
}

/** Same shape as {@link InitiativeApplicationForm} `addAuthor`. */
export function createEmptyAuthorRow(): Author {
  return {
    id: Date.now(),
    name: '',
    dob: '',
    workplace: '',
    title: '',
    qualification: '',
    contributionPercent: 0,
  };
}

export function normalizeContributionPercent(value: string | number | boolean): number {
  if (typeof value === 'boolean') return 0;
  const n = typeof value === 'string' ? Number(value) : Number(value);
  return Number.isFinite(n) ? n : 0;
}
