import type { InitiativeDraft } from '@/components/applicant/initiative-draft/types';
import { emptyInitiativeDraft } from '@/components/applicant/initiative-draft/types';
import type { ApplicationFormState, InitiativeFormState } from '@/components/applicant/initiativeFormTypes';

export type ReviewDraftTabs = {
  report?: Record<string, unknown>;
  application?: Record<string, unknown>;
  contribution?: Record<string, unknown>;
};

/**
 * Builds an {@link InitiativeDraft} from persisted review tabs so DOCX preview matches applicant ReviewPanel data.
 */
export function buildInitiativeDraftFromReviewTabs(caseId: string, tabs: ReviewDraftTabs | undefined): InitiativeDraft {
  const base = emptyInitiativeDraft(caseId.trim() || 'review');
  const app = tabs?.application as Partial<ApplicationFormState> | undefined;
  const rep = tabs?.report as Partial<InitiativeFormState> | undefined;

  return {
    ...base,
    draftId: caseId.trim() || base.draftId,
    updatedAt: new Date().toISOString(),
    application: {
      ...base.application,
      ...(app ?? {}),
      textbookEvidenceFile: null,
      researchEvidenceFile: null,
      technicalEvidenceFile: null,
    },
    report: {
      ...base.report,
      ...(rep ?? {}),
    },
  };
}
