/**
 * Orchestrates draft save → PDF render → multipart submit.
 * Keeps ReviewPanel focused on UI; submission steps stay testable in one place.
 */
import { renderFullDraftPdfBlob } from '@/components/applicant/initiative-draft/pdfExport';
import {
  submitInitiativePdf,
  type SubmitInitiativeMetadata,
  type SubmitInitiativeResponse,
} from '@/components/applicant/submitInitiativePdf';
import type { InitiativeDraft } from '@ump/shared';

function safePdfBaseName(initiativeName: string, fallbackId: string): string {
  const raw = initiativeName.trim() || fallbackId;
  const cleaned = raw.replace(/[^a-zA-Z0-9_\-\u00C0-\u024F\s]+/g, '-').trim();
  return cleaned || 'ho-so-sang-kien';
}

export interface SubmitInitiativeWorkflowInput {
  draft: InitiativeDraft;
  /** Initiative `case_code` — required to embed 2.1/2.2 evidence PDFs from MinIO in the rendered PDF. */
  initiativeCaseId?: string | null;
  metadata: SubmitInitiativeMetadata;
  onSaveAllDrafts?: (payload: {
    report: Record<string, unknown>;
    application: Record<string, unknown>;
    contribution: Record<string, unknown>;
  }) => Promise<void>;
  contributionDraft?: Record<string, unknown>;
}

/**
 * Persists all tabs (when handler provided), builds the full PDF, uploads to the API.
 */
export async function runInitiativeSubmitWorkflow(
  input: SubmitInitiativeWorkflowInput,
): Promise<SubmitInitiativeResponse> {
  const { draft, metadata, onSaveAllDrafts, contributionDraft, initiativeCaseId } = input;

  if (onSaveAllDrafts) {
    await onSaveAllDrafts({
      report: draft.report as unknown as Record<string, unknown>,
      application: draft.application as unknown as Record<string, unknown>,
      contribution: contributionDraft ?? {},
    });
  }

  const initiativeName =
    draft.application.initiativeName?.trim() || draft.report.initiativeName?.trim() || '';
  if (!initiativeName) {
    throw new Error('Vui lòng điền tên sáng kiến ở Đơn hoặc Báo cáo trước khi nộp.');
  }

  const blob = await renderFullDraftPdfBlob(draft, initiativeCaseId);
  const base = safePdfBaseName(initiativeName, draft.draftId);
  const fileName = `${base}.pdf`;

  const resolvedCase = initiativeCaseId?.trim() || metadata.initiativeCaseId?.trim();
  return submitInitiativePdf(blob, fileName, {
    ...metadata,
    initiativeCaseId: resolvedCase || metadata.initiativeCaseId,
    caseId: resolvedCase ?? metadata.caseId,
  });
}
