import type { InitiativeDraft } from '@/components/applicant/initiative-draft/types';
import { buildTemplateDataFromDraft } from '@/components/applicant/initiative-draft/draftToTemplateData';
import {
  toFullApplicationJson,
  toFullContributionJson,
  toFullReportJson,
} from '@/components/applicant/initiative-draft/draftJsonFullShape';
import { buildOfficialBieuMauFromDraft } from '@/components/applicant/initiative-draft/mapDraftToOfficialBieuMau';

/**
 * Single JSON payload for Word templates + archival: flat `templateData` for placeholders,
 * plus normalized `application` / `report` / `contribution` trees (same shape as per-tab exports).
 */
export function buildDocxTemplateExportBundle(
  draft: InitiativeDraft,
  contribution: Record<string, unknown> | null | undefined,
  options?: { caseId?: string },
) {
  const app = draft.application as unknown as Record<string, unknown>;
  const rep = draft.report as unknown as Record<string, unknown>;
  const cont = (contribution ?? {}) as Record<string, unknown>;

  return {
    meta: {
      exportedAt: new Date().toISOString(),
      caseId: options?.caseId ?? null,
      draftId: draft.draftId,
      draftUpdatedAt: draft.updatedAt,
      version: 1 as const,
      description:
        'templateData: flat keys for DOCX placeholders; application/report/contribution: full form trees; officialBieuMau: nested Vietnamese keys aligned with public/assets/bieu_mau_sang_kien_template.json and be01.',
    },
    templateData: buildTemplateDataFromDraft(draft, contribution),
    /** Nested official form — same semantics as `bieu_mau_sang_kien_template.json`; backend can store or convert to be01 `data_blank` snake_case. */
    officialBieuMau: buildOfficialBieuMauFromDraft(draft, contribution),
    application: toFullApplicationJson(app),
    report: toFullReportJson(rep),
    contribution: toFullContributionJson(cont),
  };
}
