import type { ApplicationFormState } from './initiativeFormTypes';
import type { InitiativeFormState } from './initiativeFormTypes';
import { parseContentSummaryToSection42 } from './reportContentSummaryMerge';

/** Báo cáo §4.2 fields that roll into Đơn §4 `contentSummary` (merged + labeled). */
export type ReportSection42Key =
  | 'purpose'
  | 'implementationSteps'
  | 'firstAppliedUnit'
  | 'conditions'
  | 'achievedResult';

/**
 * Builds a patch for báo cáo §4.2 from đơn `contentSummary` (parsed blocks).
 * `conditions` / `trialEvaluation` on the application are still kept in sync separately when edited alone.
 */
export function buildReportSection42PatchFromApplication(
  app: Pick<ApplicationFormState, 'contentSummary'>,
  report: InitiativeFormState,
): Partial<Pick<InitiativeFormState, ReportSection42Key>> | null {
  const parsed = parseContentSummaryToSection42(app.contentSummary ?? '');
  const patch: Partial<Pick<InitiativeFormState, ReportSection42Key>> = {};
  let dirty = false;
  (Object.entries(parsed) as [ReportSection42Key, string][]).forEach(([key, v]) => {
    const next = v ?? '';
    if ((report[key] ?? '') !== next) {
      patch[key] = next;
      dirty = true;
    }
  });
  return dirty ? patch : null;
}
