import { apiClient } from "@/shared/api/client";
import { buildDocxTemplateExportBundle } from "@/components/applicant/initiative-draft/buildDocxTemplateExportBundle";
import { buildOfficialBieuMauFromDraft } from "@/components/applicant/initiative-draft/mapDraftToOfficialBieuMau";
import type { InitiativeDraft } from "@/components/applicant/initiative-draft/types";

export interface ReviewDocumentPayload {
  caseId: string;
  officialBieuMau: Record<string, unknown>;
  templateData?: Record<string, unknown>;
  fullBundle?: Record<string, unknown>;
}

export async function persistReviewDocumentBundle(
  draft: InitiativeDraft,
  contributionDraft?: Record<string, unknown> | null,
  explicitCaseId?: string,
): Promise<ReviewDocumentPayload> {
  const caseId = (explicitCaseId || draft.draftId || "").trim();
  if (!caseId) throw new Error("Thiếu caseId để lưu JSON ReviewPanel.");
  const fullBundle = buildDocxTemplateExportBundle(draft, contributionDraft, { caseId }) as Record<
    string,
    unknown
  >;
  const templateData = (fullBundle.templateData ?? {}) as Record<string, unknown>;
  const officialBieuMau = buildOfficialBieuMauFromDraft(draft, contributionDraft) as Record<string, unknown>;
  return apiClient.post<ReviewDocumentPayload>(`/api/v1/review-documents`, {
    caseId,
    officialBieuMau,
    templateData,
    fullBundle,
  });
}

export async function getLatestReviewDocumentBundle(caseId: string): Promise<ReviewDocumentPayload> {
  const rows = await apiClient.get<{ data: ReviewDocumentPayload[] }>(
    `/api/v1/review-documents?caseId=${encodeURIComponent(caseId)}&limit=1`,
  );
  const latest = Array.isArray(rows?.data) ? rows.data[0] : undefined;
  if (!latest) throw new Error("Không tìm thấy Review JSON.");
  return latest;
}

