import type { DraftContextValue } from './DraftContext';
import type { InitiativeDraft } from './types';
import type { Author } from './initiativeFormTypes';

function defaultFirstAuthor(): Author {
  return {
    id: 1,
    name: '',
    dob: '',
    workplace: '',
    title: '',
    qualification: '',
    contributionPercent: 100,
  };
}

/**
 * Display name for «tác giả chính / đại diện nhóm tác giả sáng kiến»: Đơn tác giả thứ nhất if set, else báo cáo §2.2.
 */
export function canonicalMainAuthorFromDraft(draft: InitiativeDraft): string {
  const first = draft.application.authors[0]?.name;
  if (typeof first === 'string' && first.trim()) return first.trim();
  return (draft.report.representativeAuthor ?? '').trim();
}

/** Writes báo cáo §2.2 + dòng ký (`authorName`) và Đơn `authors[0].name` cùng một lúc. */
export function pushMainAuthorToDraft(draftCtx: DraftContextValue, name: string): void {
  draftCtx.updateReport({ representativeAuthor: name, authorName: name });
  const authors = draftCtx.draft.application.authors;
  const first = authors[0] ?? defaultFirstAuthor();
  const rest = authors.length > 0 ? authors.slice(1) : [];
  void draftCtx.updateApplication({
    authors: [{ ...first, name }, ...rest],
  });
}

/**
 * If Đơn and báo cáo drift, prefer Đơn tên tác giả 1; if Đơn trống, copy from báo cáo.
 */
export function reconcileRepresentativeAuthorSlices(draftCtx: DraftContextValue, readOnly: boolean): void {
  if (readOnly) return;
  const draft = draftCtx.draft;
  const a0 = draft.application.authors[0];
  const rawFirst = typeof a0?.name === 'string' ? a0.name : '';
  const firstName = rawFirst.trim();
  const reportRep = draft.report.representativeAuthor?.trim() ?? '';
  const reportAuth = draft.report.authorName?.trim() ?? '';
  if (firstName && (reportRep !== firstName || reportAuth !== firstName)) {
    draftCtx.updateReport({ representativeAuthor: rawFirst, authorName: rawFirst });
    return;
  }
  if (!firstName && reportRep) {
    const authors = draft.application.authors;
    const first = authors[0] ?? defaultFirstAuthor();
    const rest = authors.length > 0 ? authors.slice(1) : [];
    void draftCtx.updateApplication({
      authors: [{ ...first, name: reportRep }, ...rest],
    });
  }
}
